如何在Haskell中正确使用foldr? [英] How to use foldr correctly in Haskell?
问题描述
correctCards :: [Card] - >我试图编写一个表现如下的函数: [卡片] - > Int
它需要两张卡片清单并检查有多少张卡片相同。这是我的代码:
correctCards答案猜测= foldr步骤acc猜测
其中
acc = 0
步骤acc猜测
| elem(head guess)答案= acc + 1
|否则= acc
但是类型不匹配。有人能告诉我我错了哪里?谢谢。
查看 foldr
的类型:
foldr ::(a - > b - > b) - > b - > [a] - > b
现在,这意味着您提供的函数必须是 a - > b - > B'/ code>。给出以下代码:
foldr step 0 cards
- cards :: [Card]
- - 0 ::整数
- step :: ???
step 应该是什么类型?根据我们的论点,
a
应该是卡片
和 b
应该是整数
:
- 具体类型的`foldr` in这种情况下
foldr ::(Card - > Integer - > Integer) - >整数 - > [卡片] - >整数
因此, step 应该有类型
(卡 - >整数 - >整数)
。将这个和你的步骤函数比较:
step acc guess
| elem(head guess)答案= acc + 1
|否则= acc
在这种情况下 step
是整数 - > [卡片] - >整数
。这不是正确的类型。相反,你想
step guess acc
| elem guess answer = acc + 1
|否则= acc
请注意 step 一个单个,而不是整个列表。
I'm trying to write a function which behave like this:
correctCards :: [Card] -> [Card] -> Int
It takes two lists of type Card and check for how many cards are the same. Here is my code:
correctCards answer guess = foldr step acc guess
where
acc = 0
step acc guess
| elem (head guess) answer = acc + 1
| otherwise = acc
But the types are not match. Can someone tell me where I went wrong? Thanks.
Have a look at foldr
's type:
foldr :: (a -> b -> b) -> b -> [a] -> b
Now, that means that the function you supply must be of type a -> b -> b
. Given the following code:
foldr step 0 cards
-- cards :: [Card]
-- 0 :: Integer
-- step :: ???
what should the type of step
be? Given by our arguments, a
should be Card
and b
should be Integer
:
-- concrete type of `foldr` in this case
foldr :: (Card -> Integer -> Integer) -> Integer -> [Card] -> Integer
Therefore, step
should have the type (Card -> Integer -> Integer)
. Compare this to your step function:
step acc guess
| elem (head guess) answer = acc + 1
| otherwise = acc
In this case step
is Integer -> [Card] -> Integer
. And that's not the correct type. Instead, you want
step guess acc
| elem guess answer = acc + 1
| otherwise = acc
Note that step
only takes a single, not a whole list.
这篇关于如何在Haskell中正确使用foldr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!