开发者

How to solve these Haskell Kind errors

So I've been messing around with Haskell, and I've come across this strange error in my code.

" 'IO' is not applied to enough type arguments

Expected kind '?', but 'IO' has kind '->'

In the type signature for 'loop': loop :: State -> IO"

Here is the Code

import System.IO
data State = State [Int] Int Int deriving (Show)

main = do
   loop (State [] 0 0)

loop::State -> IO
loop state = do
   putStr "file: "
   f <- getLine
   handle <开发者_运维百科;- openFile f ReadMode
   cde <- hGetContents handle
   hClose handle
   putStrLn cde
   loop state

How do I fix this error? Also, any insight on kinds would be greatly appreciated.


IO is a type constructor, which means that it needs an argument in order to become a type. So:

IO Int
IO String
IO ()

are types, but IO by itself is not.

The kind of IO is * -> *, which is like saying it is a function that takes a type and returns a type.

I would suggest changing

loop :: State -> IO

to

loop :: State -> IO ()

(() is the "unit type", it has only one value (also called ()), and is typically used where void would be used in C-like languages)


IO is a type constructor, not a full type. You should declare

loop :: State -> IO ()

where () is the unit type; the type with only one value, also spelled (). That's the appropriate type for an eternal loop or any other function that does not return a (meaningful) value.


As others have mentioned, IO is a type constructor, not a type. So you have to apply it to some other type. A value of type IO Foo means that it is a computation which potentially does some I/O and then returns a value of type Foo.

luqui and larsman suggested that you should use () as a return value. I think the following type is a better alternative for a function that loops forever:

loop :: String -> IO a

Note that the function now is polymorphic in the return value. This type is much more informative than having it return (). Why? Because a function of this type must be a looping function. There is no way to implement a terminating function with this type. A user of this function will see immediately from the type that it is a looping function. So you get some documentation for free with this type.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜