开发者

Haskell: Why is the type inferred by GHC for main method not quite complete?

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 arg开发者_运维问答ument. <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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜