【问题标题】:How to recursively iterate through a list of 3-tuples in Haskell如何递归遍历 Haskell 中的三元组列表
【发布时间】:2019-03-18 18:52:47
【问题描述】:

我有一个三元组列表[(Int, Int, Int)]

我编写了以下辅助函数。

--This function is used to check if the first element is over 20    
checkValue :: (Int, Int, Int) -> Bool  
checkValue (x, _, _) = x  > 20


--This function is used to set the 3-tuple to return (50, 50, 50)
setValue :: (Int, Int, Int) -> (Int, Int, Int)
setValue a = (50, 50, 50)

我的目标是遍历 3 元组列表并应用我的辅助函数。

对于列表中的每个项目

  • 运行 checkValue。

  • 如果 checkValue = true,则将 setValue 应用于当前元组。

  • 继续

所以基本上如果我有这个[(0, 0, 0)(30,15,0)] 它会返回[(0, 0, 0)(50, 50, 50)]

有人能指出我正确的方向吗,我被困了一段时间。

【问题讨论】:

标签: haskell recursion functional-programming


【解决方案1】:

如果你想使用递归,那么你可以这样做;

modif :: [(Int, Int, Int)] -> [(Int, Int, Int)]
modif []                 = []
modif (t@(x, _, _) : ts) = case x > 20 of
                           True -> (50, 50, 50) : modif ts
                           _    -> t : modif ts

*Main> modif [(0, 0, 0),(30,15,0)]
[(0,0,0),(50,50,50)]

t@(x, _, _) 部分代表在元组的第一个元素上进行模式处理 x 并将整个事物命名为 t

【讨论】:

    猜你喜欢
    • 2019-03-17
    • 1970-01-01
    • 2018-02-20
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 2014-03-01
    • 1970-01-01
    相关资源
    最近更新 更多