-1

我有一个元组 (1, 2, 3) 并且想要获取第三个元素,但是,我不断收到类型错误。

请看下面的代码:

third (hd : tl) = snd tl
third tpl = head$tail$tail tpl

如何修复正在发生的类型错误并正确获取第三个元素?

4

2 回答 2

3

元组不是列表

在您的代码中,您正在操作列表:head并且tail所有工作都在列表上。所以

third tpl = head . tail . tail . tail $ tpl
third' (_:_:x:_) = x

会给你第三个元素。

a = [1, 2, 3]

>> third a
   3
>> third (1, 2, 3)
   Error expecting list, but got tuple

相反,您将不得不使用类型的函数

thd :: (a, b, c) -> c

这个函数在标准库中不存在,它完全是微不足道的

thd (_, _, a) = a

就是这样:)

于 2013-10-25T02:57:30.043 回答
2

您将元组与列表混淆:

-- Tuples: Fixed length, mixed types, uses parenthesis
myTuple :: (Int, String)
myTuple = (1, "Hello")

-- Lists: Variable length, single type, uses square brackets
myList :: [Int]
myList = [1, 2, 3, 4]

-- Pattern matching a 3-tuple
isRightTriangle :: (Int, Int, Int) -> Bool
isRightTriangle (a, b, c) = a^2 + b^2 == c^2

-- Pattern matching a 2-tuple
name :: (String, Int) -> String
name (n, a) = n
-- or: name = fst

age :: (String, Int) -> Int
age (n, a) = a
-- or: age = snd

-- Pattern matching a list
thirdElem :: [a] -> a
thirdElem (x1:x2:x3:xs) = x3
thirdElem _ = error "List must have at least 3 elements"
-- or: thirdElem xs = head $ tail $ tail xs

如果你还没有,你应该看看Learn You a Haskell For Great Good。阅读 Haskell 的介绍非常有趣,从字符串、元组、数字和列表等基本类型开始。

于 2013-10-25T02:57:21.153 回答