非常基本的任务使用foldr [英] Very basic task using foldr

查看:125
本文介绍了非常基本的任务使用foldr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  foldr(:) [] 1我只是在一些讲义中使用了一个非常简单的示例2 

期待结果

  [1,2] 

但是,我收到一个错误。每当我尝试使用++或:作为给予foldr的函数时,我都会收到一个错误。



显然我犯了一些非常明显的错误,但我似乎仍然无法找到它。



任何人都可以帮忙吗?

解决方案

code> foldr 通过传递两个参数 1 2 就像一个可变参数函数>而不是 [1,2]



遇到这种麻烦时,只需检查函数的类型。您可以在GHCi中做到这一点:

  Prelude> :t foldr 
foldr ::(a - > b - > b) - > b - > [a] - > b

所以你看到第一个参数应该是一个函数(a - > b - > b)。你使用了(:),这就是o.k.您也可以检查部分应用函数的类型:

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

用<$ $替换 b c $ c> [a] 给了我们:

  Prelude> :t foldr(:) 
foldr(:) :: [a] - > [a] - > [a]

接下来,您给了 [] 作为基本案例。

  Prelude> :t foldr(:) [] 
foldr(:) [] :: [a] - > [a]

所以结果函数的类型是 [a] - > ; [α] 。你应该怎么做?你必须通过一个列表来获取列表!传递参数列表 [1,2]

  Prelude> :t foldr(:) [] [1,2] 
foldr(:) [] [1,2] :: Num a => [b]

被类型检查器接受并产生结果:

  Prelude> foldr(:) [] [1,2] 
[1,2]

I希望这有助于类型 - 调试你的程序...


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?

解决方案

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

这篇关于非常基本的任务使用foldr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆