【问题标题】:A Haskell List Involving Recursion and High Order Functions涉及递归和高阶函数的 Haskell 列表
【发布时间】:2018-04-02 06:56:38
【问题描述】:

现在我有了这段代码,它接受一个列表并对第一个元素执行某些操作,然后对其他每个元素执行操作。它返回一个转换后的元素列表。我遇到的问题是我想要一个包含未转换和已转换元素的列表。这是我到目前为止所拥有的:

applyToEveryOther :: (a -> b) -> [a] -> [b]
applyToEveryOther _ [] = []
applyToEveryOther f [x] = [f x]
applyToEveryOther f (x:y:xs) = f x : y : applyToEveryOther f xs

它给我的错误是函数的: y 部分存在问题

【问题讨论】:

  • 为了将来参考,您应该在问题中包含错误消息。它不仅可以帮助那些试图回答的人,还可以帮助人们在将来遇到类似问题并尝试搜索错误消息时找到您的问题。

标签: list function haskell recursion


【解决方案1】:

如果我理解正确,您想要原始值和转换后的值。

但是,评估 applyToEveryOther (+3) [0,1,2] 会返回 [3,1,5]。如果您想要 [0,3,1,4,2,5] 作为结果,请尝试

applyToEveryOther _ [] = []
applyToEveryOther f [x] = [x,f x]
applyToEveryOther f (x:xs) = x: f x : applyToEveryOther f xs

【讨论】:

    【解决方案2】:

    当我尝试您的代码时,我收到以下错误消息(诚然有些冗长且令人困惑):

    EveryOther.hs:4:42: error:
        • Couldn't match type ‘b’ with ‘a’
          ‘b’ is a rigid type variable bound by
            the type signature for:
              applyToEveryOther :: forall a b. (a -> b) -> [a] -> [b]
            at EveryOther.hs:1:22
          ‘a’ is a rigid type variable bound by
            the type signature for:
              applyToEveryOther :: forall a b. (a -> b) -> [a] -> [b]
            at EveryOther.hs:1:22
          Expected type: [a]
            Actual type: [b]
        • In the second argument of ‘(:)’, namely ‘applyToEveryOther f xs’
          In the second argument of ‘(:)’, namely
            ‘y : applyToEveryOther f xs’
          In the expression: f x : y : applyToEveryOther f xs
        • Relevant bindings include
            xs :: [a] (bound at EveryOther.hs:4:26)
            y :: a (bound at EveryOther.hs:4:24)
            x :: a (bound at EveryOther.hs:4:22)
            f :: a -> b (bound at EveryOther.hs:4:19)
            applyToEveryOther :: (a -> b) -> [a] -> [b]
               (bound at EveryOther.hs:2:1)
    

    但是,值得尝试弄清楚 GHC 在这里所说的内容。根据第二个要点,GHC 正在处理子表达式y : applyToEveryOther f xs,并专门查看该表达式中: 运算符的第二个参数(即applyToEveryOther f xs。它预计该表达式的类型为[a],但是表达式的实际类型是[b]。

    这里,a 和 b 都是“刚性”类型,这意味着它们是由程序员明确指定的。 GHC 还指出,在相关绑定中,y 的类型为 a。

    所以,总而言之,您要求 GHC 评估表达式:

    y : applyToEveryOther f xs
    

    您已经指定 y 的类型为 a 和 applyToEveryOther f xs 的类型为 [b],而 GHC 拒绝这样做,因为 Haskell 中的列表不能混合两种不同的类型。

    这就是整个问题的关键所在。您想将[a] 列表中的一些元素从a 转换为b,但是您想返回as 和bs 的混合列表。 Haskell 做不到!

    您的函数可以工作的唯一方法是更改​​签名以使a 和b 是同一类型:

    applyToEveryOther :: (a -> a) -> [a] -> [a]
    

    您的代码将正常工作。

    另一种“发现”正确签名的方法是将其排除在外,让 Haskell 推断出最普​​遍的可能签名。如果您将代码(没有显式签名)加载到 GHCi 并询问类型,您会得到:

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

    这是此函数最通用的可能类型。

    【讨论】:

    • 男人中的神!谢谢
    猜你喜欢
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 2014-08-16
    • 2014-01-22
    • 2017-11-12
    • 1970-01-01
    • 2017-04-21
    相关资源
    最近更新 更多