Couldn't match expected type `a' with actual type `[a]'

前端 未结 3 2250
隐瞒了意图╮
隐瞒了意图╮ 2021-02-14 10:14

I was able to execute the following code flawlessly

myLast :: [a] -> a
myLast [] = error \"Can\'t call myLast on an empty list!\"
myLast (x:_) = x
         


        
3条回答
  •  醉酒成梦
    2021-02-14 10:39

    Having an understanding of what : really is will help decrypt the error message. : can be thought of as a function which takes an element and a list, and returns a list that whose first element is the first argument and the rest of it is the second argument, or:

    (:) :: a -> [a] -> [a]
    

    Getting to your function, you wrote myLast :: [a] -> a; however, the type of myLast (_:x) = x is myLast :: [a] -> [a] since the second argument of : (which you named x) is itself a list.

    Additionally, in general when you don't understand something in Haskell, you should take a look at it's type first using :t in GHCI.

提交回复
热议问题