【问题标题】:Trying to understand recursion through a list of integers试图通过整数列表来理解递归
【发布时间】:2016-02-09 13:57:06
【问题描述】:

我目前正在学习如何在 Haskell 中使用递归,并且我正在尝试了解如何遍历整数列表中的每个元素并将它们取反。到目前为止,我可以做到这一点,但只能在列表的最后一个元素上,所以我知道错误在最后一行。遍历列表中每个元素而不仅仅是最后一个元素的最佳方法是什么?

negation :: [Int] -> [Int]
negation [] = []
negation [n] = [-n]
negation(x:xs) = negation xs

【问题讨论】:

    标签: list haskell recursion negation


    【解决方案1】:

    尝试使用cons 运算符: 将取反的数字放在列表的前面。

    negation (x:xs) = -x : negation xs
    

    如果你这样做,你可以摆脱第三行。

    【讨论】:

    • 啊我明白了。非常感谢您的回复!
    【解决方案2】:

    好吧,编写函数的最佳方法是:

    negation :: [Int] -> [Int]
    negation xs = map negate xs
    
    {- Example:
    
    >>> map negate [1..5]
    [-1,-2,-3,-4,-5]
    -}
    

    练习:编写你自己的map

    myMap :: (a -> b) -> [a] -> [b]
    myMap _ [] = _fillMeIn
    myMap f (x:xs) = _fillMeIn
    

    【讨论】:

      【解决方案3】:

      简单的地图:

        Prelude> let negatList= map (*(-1))
      

      例子:

        Prelude> negatList []
        []
        Prelude> negatList [1]
        [-1]
      

      使用递归:

       negation :: [Int] -> [Int]
       negation [] = []
       negation(x:xs) = -x:negation xs
      

      【讨论】:

        【解决方案4】:

        正如之前的回答中提到的,最好的方法是使用高阶函数,如下所示

        negation xs = map negate xs
        

        尽可能使用高阶函数。它是 wiki.haskell.org 上的通用 Haskell 编程指南之一,它简化了您的代码。

        【讨论】:

          猜你喜欢
          • 2015-03-23
          • 1970-01-01
          • 2011-11-09
          • 2021-05-15
          • 2015-03-10
          • 2020-10-17
          • 1970-01-01
          • 2016-09-07
          • 1970-01-01
          相关资源
          最近更新 更多