Using Haskell's “Maybe”, type declarations [beginner's question]

ⅰ亾dé卋堺 提交于 2019-11-29 10:43:51

The type of qqq is:

qqq :: Show a => Maybe a -> IO ()

That means that qqq takes one parameter of type Maybe a and returns an IO action without a value, with the constraint that a implements the Show typeclass. To find out what Show is, you can use :i Show in ghci.

Show is a typeclass which requires that a value of the type can be converted to a string. qqq has the constraint because print wants to print out the value (print has type Show a => a -> IO ()). Maybe is not a typeclass but a data type. You can read more about typeclasses here.

You can let GHC deduce the type signature either by typing the function in a .hs file, then loading the file with ghci (ghci Myfile.hs), and then typing :t qqq for displaying the type. You can also define the function in the interactive session with let qqq n = case n of { Nothing -> print "abc"; Just x -> print "def" >> print x } (it looks a bit different because the function definition has to be on one line in ghci, but the meaning is the same).

When main calls qqq with qqq (Just 43), it is clear the concrete type of Maybe a is a numeric type (ghci defaults to Integer), so qqq has the concrete type of Maybe Integer -> IO (). However, main calls qqq with qqq Nothing, a could be anything (it is ambiguous) and ghci reports an error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!