【问题标题】:Access tuples data that is inside a list访问列表内的元组数据
【发布时间】:2023-03-29 16:58:01
【问题描述】:

如果我想在我的函数中访问/引用一个字符参数,我只是这样做:

myFunc :: Char -> Bool
myFunc c = ... --Here I use 'c' to work with my Char parameter

使用列表:

myList :: [Int] -> [Int]
myList l = ... --I can access the list with 'l'. 

现在,我如何访问/工作/引用列表中的元组数据:

myFunc :: [(Int, Int)] -> [(Int, Int)] --Receive a list of tuple as parameter
myFunc ?? = ... --How may I access the tuple element ? How may I access its data. Just use a letter there and try to work with `fst` or `snd` does not work.

更新

myFunc :: [(Int, Int)] -> [(Int, Int)]
myFunc  [] = [(0, 0)]
myFunc ((x,y):rest) = x --Error here:  
Couldn't match expected type `[(Int, Int)]' with actual type `Int' In the  expression: x

【问题讨论】:

  • 您收到错误是因为xInt 类型的值。您的类型签名表明您的函数正在返回 [(Int, Int)] 类型的值,但您实际上正在返回 Int 并因此返回错误。

标签: list haskell tuples


【解决方案1】:

您实际上是在问如何进行模式匹配。在您的情况下,这是执行此操作的一般方法:

myFunc :: [(Int, Int)] -> [(Int, Int)]
myFunc [] = undefined
myFunc ((x,y):[]) = undefined
myFunc ((x,y):rest) = undefined

模式((x,y):[]) 将匹配只有一个元素的列表。 x 引用元组中的第一个元素,y 引用第二个元素。同样,在((x,y):rest) 模式中,rest 指的是除了第一个(或头)元素之外的列表的其余部分。

另一种类似但功能较弱的方法是这样的:

myFunc :: [(Int, Int)] -> [(Int, Int)]
myFunc [] = undefined
myFunc (first:[]) = undefined
myFunc (first:rest) = undefined

(first:rest) 模式中,列表的头元素由变量first 引用。现在要访问其中的元组,您可以使用 fstsnd 组合器。

【讨论】:

  • 我试过了:myFunc ((x,y):rest) 但我得到了这个错误:Couldn't match expected type [(Int, Int)] with actual type Int In the expression: x
  • @PlayHardGoPro 您可以发布您尝试过的完整代码吗?
  • 你这个摇滚人!最后一件事。假设我想为每个值添加 +1,我现在如何使用高阶函数来完成它,但我想递归地完成它。如何再次调用该函数并跳到下一个元组?
  • @PlayHardGoPro 一些提示:您最初像(x + 1, y + 1) 一样递增元组,然后递归地将rest 参数传递给自身。将它们与列表构造函数 : 粘合在一起,您的函数几乎准备就绪。
猜你喜欢
  • 2013-08-17
  • 1970-01-01
  • 1970-01-01
  • 2018-07-26
  • 1970-01-01
  • 2022-11-13
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多