2017-07-26 44 views
6

只許成功試想一下,我有以下列表:應用兩個摺痕或getter和當兩個成功

lst :: [(Bool, Maybe Integer)] 
lst = [(True, Just 3), (True, Nothing), (False, Just 12)] 

使用鏡頭庫,我想提取的元組的元素,但我只希望它成功當第二個元素是Just。我想要一些光,split認爲是這樣的:

> lst ^.. folded.split (_1.to not) (_2._Just) 
[(False, 3), (True, 12)] 

我可以實現自己split像這樣:

split :: Getting (First a) s a -> Getting (First b) s b -> Fold s (a, b) 
split a b = folding (\x -> (,) <$> (x ^? a) <*> (x ^? b)) 

...這似乎工作。不過,這似乎是我必須重新發明輪子。鏡頭庫已經提供了一種以同樣好的方式實現這一點的東西嗎?

回答

6

aside組合子需要Prism的作品在元組的所述第二部件,並返回一個Prism的作品在整個元組:

ghci> lst ^.. folded.aside _Just 
[(True,3),(False,12)] 

所得棱鏡比賽當組件被匹配,否則失敗。

tobimap結合,我們可以重現你的例子:

ghci> lst ^.. folded.aside _Just.to (bimap not id) 
[(False,3),(True,12)] 

要在第一部分工作,我們可以使用swapped

ghci> [(Just 3,False)]^..folded.swapped.aside _Just.swapped 
[(3,False)]