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

前端 未结 3 2251
隐瞒了意图╮
隐瞒了意图╮ 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:28

    You're declaring the input to be a list of type [a], and the rest to be of type a.

    A list of type [a] in Haskell consists of a head of type a and a tail, a list of type [a]. The cons constructor : takes the head and tail as its arguments.

    When you deconstruct a list as (x:y), x is the head and y is the tail. So in your second code fragment, you're binding the tail of the list, which has the list type [a], when your type signature requires that you return a value of type a (the head being one example).

提交回复
热议问题