Haskell在3部分元组上执行fst

时间:2013-03-28 14:00:08

标签: haskell

我有以下Haskell元组:

       [("string",1,1)]

我需要提取第一个元素,显然使用'fst'不会在这里工作,因为有3个组件。

最好的使用方法是什么? sel

5 个答案:

答案 0 :(得分:15)

你可以输入你自己的函数(我们将使用模式匹配):

fst3 :: (a, b, c) -> a
fst3 (x, _, _) = x

你就像使用它一样:

fst3 ("string", 1, 1)

答案 1 :(得分:5)

sel可以按以下方式使用:

$ cabal install tuple
$ ghci
>>> :m +Data.Tuple.Select
>>> sel1 ("string",1,1)
"string"

它与map

的任何其他功能一样
>>> map sel1 [("One",1,0),("Two",2,0),("Three",3,0)]
["One","Two","Three"]

主要优点是它适用于更大的元组

>>> sel1 ("string",1,1,1)
"string"

以及标准元组

>>> sel1 ("string",1)
"string"

因此无需单独处理它们。


更多例子:

>>> map sel2 [("One",1,0),("Two",2,0),("Three",3,0)]
[1,2,3]
(0.06 secs, 4332272 bytes)
>>> map sel3 [("One",1,0),("Two",2,0),("Three",3,0)]
[0,0,0]
(0.01 secs, 2140016 bytes)
>>> map sel4 [("One",1,0),("Two",2,0),("Three",3,0)]

<interactive>:6:5:
.... error

答案 2 :(得分:4)

我只想定义一个函数

fst3 :: (a,b,c) -> a
fst3 (x,_,_) = x

这很容易理解并且没有奇怪的类型(sel1的类型是Sel1 a b => a -> b可能会让人感到困惑)

或者您可以通过模式匹配提取您感兴趣的值,如[x | (x,_,_) <- myThreeTupleList中所示。

最后,最好的解决方案是使用更结构化的数据类型!当然,字符串和两个整数具有更多的意义,并且以某种方式对其进行编码是一个好主意......

答案 3 :(得分:4)

你也可以使用 lens包裹:

> import Control.Lens
> Prelude Control.Lens> view _1 (1,2)  -- Or (1,2) ^. _1
1
> Prelude Control.Lens> view _1 (1,2,3) -- Or (1,2,3) ^. _1
1
> Prelude Control.Lens> view _1 (1,2,3,4) -- Or (1,2,3,4) ^. _1
1
> Prelude Control.Lens> view _1 (1,2,3,4,5) -- Or (1,2,3,4,5) ^. _1
1

这不仅仅适用于第一个元素

> import Control.Lens
> Prelude Control.Lens> view _2 (1,2)  -- Or (1,2) ^. _2
2
> Prelude Control.Lens> view _3 (1,2,3) -- Or (1,2,3) ^. _3
3
> Prelude Control.Lens> view _4 (1,2,3,4) -- Or (1,2,3,4) ^. _4
4
> Prelude Control.Lens> view _5 (1,2,3,4,5) -- Or (1,2,3,4,5) ^. _5
5

我还写了一个类似问题的答案,其中不仅包含元组: https://stackoverflow.com/a/23860744/128583

答案 4 :(得分:3)

你可以这样做:

Prelude> let [(a,_,_)]=[("string",1,1)]
Prelude> a
"string"