dictionary - 从记录列表生成字典

标签 dictionary record elm

BMap 对象是 BPair Elm-Records 的列表。如何构建仅包含 BPair.isEnabled == True 的那些对的 Dictionary?最终,我们需要在给定的closer的相应openerDict.get

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

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

最佳答案

简而言之,您必须:

  1. 过滤BMap以获取.isEnabled中所有具有TrueBPair
  2. 将所有列表项转换为元组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

关于dictionary - 从记录列表生成字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36991210/

相关文章:

elm - 转换关键变量名称中的字符串

Elm:在 HTML 选择中保留值的类型?

java - Stream().map() 结果作为 Collectors.toMap() 值

python - 对列表中的 Python 字典对象进行排序

record - Peoplesoft CreateRowset 相关显示记录

c# - 如何在C#中声明嵌入式结构(如delphi中的嵌入式记录)?

c# - 我们可以在 C# 8.0 中使用记录吗?

matlab - 从 Matlab 的 Map 中释放内存

python - Pyspark:重命名 DataFrame 列中的字典键

javascript - 不能 Dockerize Elm