Very basic task using foldr

我是研究僧i 提交于 2019-12-12 01:23:41

问题


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?


回答1:


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...



来源:https://stackoverflow.com/questions/18463019/very-basic-task-using-foldr

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