Reputation: 1003
I just used a very simple example used in some lecture notes with my ghci:
foldr (:) [] 1 2
expecting the result
[1,2]
However, I get an error. I get an error everytime when I try to use ++ or : as the function given to foldr.
Apparently I am making some pretty obvious mistake but I still cannot seem to find it.
Can anyone help?
Upvotes: 0
Views: 213
Reputation: 3805
You used foldr
like a variadic function by passing it two arguments 1
and 2
instead of [1, 2]
.
When you run into trouble like that, just check the function's type. You can do that in GHCi:
Prelude> :t foldr
foldr :: (a -> b -> b) -> b -> [a] -> b
So you see that the first argument should be a function (a -> b -> b)
. You used (:)
for that, which is o.k. You can check the type of the partially applied function as well:
Prelude> :t (:)
(:) :: a -> [a] -> [a]
Substituting b
with [a]
gives us:
Prelude> :t foldr (:)
foldr (:) :: [a] -> [a] -> [a]
Next, you gave []
as a base case.
Prelude> :t foldr (:) []
foldr (:) [] :: [a] -> [a]
So the resulting function is of type [a] -> [a]
. What should you make of this? You have to pass it a list to get a list back! Passing the argument list [1, 2]
:
Prelude> :t foldr (:) [] [1,2]
foldr (:) [] [1,2] :: Num a => [a]
Is accepted by the type checker and yields the result:
Prelude> foldr (:) [] [1,2]
[1,2]
I hope this helps type-debugging your programs...
Upvotes: 14