我有一个类型的颜色联合,我想呈现给用户.是否可以迭代所有类型的联合值?
type Color = Red | Blue | Green | Black
colorToStirng color =
case color of
Red -> "red"
Blue -> "blue"
Green -> "green"
Black -> "black"
colorList =
ul
[]
List.map colorListItem Color -- <- this is the missing puzzle
colorListItem color =
li [class "color-" ++ (colorToString color) ] [ text (colorToString color) ]
Run Code Online (Sandbox Code Playgroud)
Gre*_*rds 12
声明函数的问题如下:
type Foo
= Bar
| Baz
enumFoo =
[ Bar
, Baz ]
Run Code Online (Sandbox Code Playgroud)
是你可能会忘记添加新的枚举.为了解决这个问题,我一直在玩这个(hacky,但比上面的想法更少hacky)的想法:
enumFoo : List Foo
enumFoo =
let
ignored thing =
case thing of
Bar -> ()
Baz -> ()
-- add new instances to the list below!
in [ Bar, Baz ]
Run Code Online (Sandbox Code Playgroud)
这样你至少会得到一个函数错误,希望不要忘记将它添加到列表中.
很不幸的是,不行.这不可能.
对于像您的Color类型一样具有有限数值的简单类型,编译器应该能够生成这样的列表.然而,就编译器而言,你的类型和类型之间没有区别
type Thing = Thing String
Run Code Online (Sandbox Code Playgroud)
迭代所有类型的值Thing将需要迭代所有类型的值String.