如何递归遍历Haskell中的三元组列表

时间:2018-10-13 23:22:48

标签: haskell recursion functional-programming

我有一个三元组--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)

的列表

我编写了以下辅助函数。

[(0, 0, 0)(30,15,0)]

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

对于列表中的每个项目

  • 运行checkValue。

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

  • 继续

所以基本上如果我有这个[(0, 0, 0)(50, 50, 50)] 它将返回{{1}}

有人能指出我正确的方向吗?在这上面停留了一段时间。

1 个答案:

答案 0 :(得分: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