如何在Haskell中正确使用foldr?

2024-02-29

我正在尝试编写一个行为如下的函数:

correctCards :: [Card] -> [Card] -> Int

它需要两个卡片类型列表并检查有多少张卡片是相同的。这是我的代码:

correctCards answer guess = foldr step acc guess
        where 
            acc = 0
            step acc guess
                | elem (head guess) answer  = acc + 1
                | otherwise                 = acc

但类型不匹配。有人能告诉我哪里错了吗?谢谢。


看一下foldr's type:

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

现在,这意味着您提供的函数必须是类型a -> b -> b。给出以下代码:

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

应该是什么类型step是?根据我们的论点,a应该Card and b应该Integer:

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

所以,step应该有类型(Card -> Integer -> Integer)。将此与your阶跃函数:

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

在这种情况下step is Integer -> [Card] -> Integer。这不是正确的类型。相反,你想要

step guess acc
     | elem guess answer = acc + 1
     | otherwise         = acc

注意step只需要一个single,不是完整列表。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Haskell中正确使用foldr? 的相关文章

随机推荐