代码之家  ›  专栏  ›  技术社区  ›  lifebalance

从记录列表生成字典

  •  2
  • lifebalance  · 技术社区  · 10 年前

    A. BMap 对象是以下项的列表 BPair 榆树记录。如何构建 Dict 仅包含以下对的词典 BPair.isEnabled == True ? 最终,我们需要 Dict.get 在相应的 opener 对于给定的 closer .

    或者,如果记录本身可以被“查询”,那么我宁愿这样做。

    type alias EnabledPair = (Char, Char) 
    type alias EnabledMap  = Dict EnabledPair  -- how to generate this? 
    
    type alias BPair = {
      opener: Char, 
      closer: Char,
      isEnabled: Bool,
      id: Int
    }
    
    type alias BMap = List BPair
    
    3 回复  |  直到 8 年前
        1
  •  3
  •   lifebalance    10 年前

    简而言之,您必须:

    1. 滤器 BMap 得到所有 BPair 具有 True 在里面 .isEnabled
    2. 将中的所有列表项转换为Tuples EnabledPair
    3. 使用 Dict.fromList 将其转换为字典
    4. 现在您可以使用 Dict.get 以检索 Maybe EnabledPair

    请考虑以下示例:

    import Graphics.Element exposing (show)
    import Dict exposing (Dict)
    
    
    type alias EnabledPair = (Char, Char) 
    
    
    type alias EnabledMap = Dict Char EnabledPair
    
    
    type alias BPair = {
      opener: Char, 
      closer: Char,
      isEnabled: Bool,
      id: Int
    }
    
    
    type alias BMap = List BPair
    
    
    testList : BMap
    testList =
      [ BPair '(' ')' True 1
      , BPair '{' '}' False 2
      , BPair '[' ']' True 3
      , BPair '<' '>' False 4
      ]
    
    
    main =
      testList
      |> List.filter (\{isEnabled} -> isEnabled == True)
      |> List.map (\{opener, closer} -> (opener, closer))
      |> Dict.fromList
       -- Dict.get will always return Maybe Char, so you have to handle that
      |> Dict.get '{'
      |> show
    
        2
  •  1
  •   lifebalance    10 年前

    此版本使用 List.Extra find 函数来更简洁地完成它。幸亏 Nick H 为了这个。

    import List.Extra as ListX
    
    matchEnabledOpenr: Char -> BPair -> Bool
    matchEnabledOpenr o bp =
      bp.isEnabled && bp.opener == o
    
    
    getClosr: Char -> List BPair -> Maybe Char
    getClosr o bmap =
      ListX.find (matchEnabledOpenr o) bmap
        |> Maybe.map .closer 
    
        3
  •  0
  •   lifebalance    10 年前

    与公认的答案形成对比的是,这里有一种方法可以完全避免生成字典。

    matchEnabledOpenr: Char -> BPair -> Maybe Char
    matchEnabledOpenr o bp = 
      case bp.isEnabled of
        True -> 
          if bp.opener == o then 
            Just bp.closer 
          else 
            Nothing 
        False -> 
            Nothing
    
    getClosr: Char -> List BPair -> Maybe Char 
    getClosr o bm =  
      List.head (List.filterMap (matchEnabledOpenr o) bm )
    
    推荐文章