Вопрос

For example, take the code written by Don Stewart in reply to some Stack Overflow question:

import Control.Monad
import qualified Data.HashTable as H
import System.Environment

main = do
  [size] <- fmap (fmap read) getArgs
  m <- H.new (==) H.hashInt
  forM_ [1..size] $ \n -> H.insert m n n
  v <- H.lookup m 100
  print v

Load it in GHCi.

:t getArgs ---> getArgs :: IO [String]
:t main    ---> main :: IO ()

Why doesn't the type signature of main reflect the fact that getArgs :: IO [String] is being called?

When you run the binary you can give an argument. <prog> 145 returns Just 100 But in GHCi, you cannot: main 145 gives error. How do you run this program in GHCi and give an argument.

Это было полезно?

Решение

The type of main is that of its final expression; print produces IO (), so that's the type of main. Intermediate types are not relevant, as (>>=) doesn't propagate anything other than the monad.

(>>=) :: Monad m => m a -> (a -> m b) -> m b

a doesn't appear in the result type (m b).

As for running your program in GHCi, take a look at the :main command.

Другие советы

You want to :set the value of args. For example:

Prelude> import System.Environment
Prelude System.Environment> getArgs
[]
Prelude System.Environment> :set args ["foo","bar"]
Prelude System.Envrionment> getArgs
["foo","bar"]

As for the type signature issue, the type of main here is determined by print v. Everything else before it is ignored via the >> operator.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top