2013-03-28 26 views
7

執行FST我有以下Haskell的元組:哈斯克爾在3元組,

 [("string",1,1)] 

我需要提取的這第一要素,顯然是在利用「FST」在這裏不會工作,因爲有3個組成部分。

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

+0

可能欺騙http://stackoverflow.com/questions/5844347/haskell-accessing-a-specific-element-in-a-元組。 –

回答

11

你可能只需要輸入自己的函數(我們將使用模式匹配)本:

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

,你使用它像:

fst3 ("string", 1, 1) 
+0

感謝您使用此解決方案。 – ZeeeeeV

+0

謝謝,這正是我一直在尋找的。 – user2214957

+1

@ user2214957如果您不知道(我認爲您是新用戶):當您決定最喜歡哪個答案時,您應該接受它作爲最佳/正確答案。 – Martinsos

3

你可以這樣做:

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

我只是定義一個函數

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

這很容易理解,不會有一個奇怪的類型(sel1類型爲Sel1 a b => a -> b這可能會造成混淆)

或者你可以提取您通過模式匹配有興趣在[x | (x,_,_) <- myThreeTupleList值。

最後,最好的解決方案是使用更結構化的數據類型!當然,字符串和兩個整數攜帶更多的含義,這是一個好主意,編碼莫名其妙......

+1

@Martinsos:這是這個函數的一個非常常見的名字;例如參見[MissingH軟件包](http://hackage.haskell.org/packages/archive/MissingH/1.1.1.0/doc/html/Data-Tuple-Utils.html)。實際上,我認爲應該在2008年將其添加到Data.Tuple中:請參閱[圖書館郵件列表上的此消息](http://comments.gmane.org/gmane.comp.lang.haskell.libraries/8841) 。 – yatima2975

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 
+0

這是否適用於任何大小的元組? – Martinsos

+1

是的,對於所有大小等於小於15的元組(因爲sel15被定義但不是sel16)。 – zurgl

+2

此限制是由於ghc tupe限制更多信息請參閱http://stackoverflow.com/questions/2978389/haskell-tuple-size-limit – zurgl

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