2016-12-06 93 views
0

我试图从子结构中获取值列表。 我有以下结构使用Control.Lens获取子列表中的值列表

("Value",[(1,"1"),(2,"2"),(3,"3"),(4,"4"),(5,"5")]) 

而且我想从列表元组的第二个元素。

[ “1”, “2”, “3”, “4”, “5”]

表达我捆扎是

视图(_2。toListOf。_2)一个

我也试过遍历。但似乎遍历在列表上有折叠效应。我需要结果作为一个列表。

Prelude Control.Lens> let a = ("Value", [(i, show i)|i<-[1..5]]) :: (String, [(Int, String)]) 
Prelude Control.Lens> a 
("Value",[(1,"1"),(2,"2"),(3,"3"),(4,"4"),(5,"5")]) 
Prelude Control.Lens> view (_2 . toListOf . _2) a 

<interactive>:36:7: error: 
    • Couldn't match type ‘[]’ with ‘Const t’ 
     Expected type: Getting t (String, [(Int, String)]) t 
     Actual type: (t -> Const t t) 
        -> (String, [(Int, String)]) -> [(String, [(Int, String)])] 
    • In the first argument of ‘view’, namely ‘(_2 . toListOf . _2)’ 
     In the expression: view (_2 . toListOf . _2) a 
     In an equation for ‘it’: it = view (_2 . toListOf . _2) a 
    • Relevant bindings include it :: t (bound at <interactive>:36:1) 

<interactive>:36:23: error: 
    • Couldn't match type ‘Const t t0’ 
        with ‘[(Int, String)] 
          -> Const (Data.Monoid.Endo [[(Int, String)]]) [(Int, String)]’ 
     Expected type: (t -> Const t t) 
        -> Getting 
          (Data.Monoid.Endo [[(Int, String)]]) 
          [(Int, String)] 
          [(Int, String)] 
     Actual type: (t -> Const t t) 
        -> ([(Int, String)] 
         -> Const (Data.Monoid.Endo [[(Int, String)]]) [(Int, String)]) 
        -> Const t t0 
    • In the second argument of ‘(.)’, namely ‘_2’ 
     In the second argument of ‘(.)’, namely ‘toListOf . _2’ 
     In the first argument of ‘view’, namely ‘(_2 . toListOf . _2)’ 
    • Relevant bindings include it :: t (bound at <interactive>:36:1) 
Prelude Control.Lens> 

回答

2

文档说:

查看值由一个getter,ISO或镜头或折叠的折叠或穿越指向在monoidal值的所有结果的结果指向。

您需要使用toListOf而不是view。例如:

toListOf (_2.traverse._2) a 

或者

a ^.. _2 . traverse . _2 

所以,toListOf不是镜头,它就像view另一家运营商,但它提取的目标的列表。

+0

工作就像一个魅力。谢谢。 – yilmazhuseyin