BMap
对象是 BPair
Elm-Records 的列表。如何构建仅包含 BPair.isEnabled == True
的那些对的 Dict
ionary?最终,我们需要在给定的closer
的相应opener
处Dict.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
最佳答案
简而言之,您必须:
- 过滤
BMap
以获取.isEnabled
中所有具有True
的BPair
- 将所有列表项转换为元组
EnabledPair
- 使用Dict.fromList将其转换为字典
- 现在您可以使用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/