简体   繁体   English

如何在Haskell中正确使用foldr?

[英]How to use foldr correctly in Haskell?

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的类型:

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

Now, that means that the function you supply must be of type a -> b -> b . 现在,这意味着您提供的函数必须是a- a -> b -> b Given the following code: 给出以下代码:

foldr step 0 cards
-- cards :: [Card]
-- 0     :: Integer
-- step  :: ???

what should the type of step be? step的类型应该是什么? Given by our arguments, a should be Card and b should be Integer : 根据我们的论点, a应该是Cardb应该是Integer

-- concrete type of `foldr` in this case
foldr :: (Card -> Integer -> Integer) -> Integer -> [Card] -> Integer

Therefore, step should have the type (Card -> Integer -> Integer) . 因此, step应该具有类型(Card -> Integer -> Integer) Compare this to your step function: 将此与您的 step函数进行比较:

step acc guess
    | elem (head guess) answer  = acc + 1
    | otherwise                 = acc

In this case step is Integer -> [Card] -> Integer . 在这种情况下, stepInteger -> [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. 需要注意的是step只需要一个单一的 ,而不是整个列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM