我正在尝试通过对问题模型进行建模中的指导在Elm中创建Palette类型。我的第一个想法是说:
type alias Palette = List Color
但这有缺点。调色板是一种颜色列表,但它也必须具有两种颜色,一种是背景色,一种是前景色。
我的第二次尝试是使用记录类型:
type alias Palette =
{ bg : Color
, fg : List Color
}
这样比较好,但是如何确保该fg
字段是包含至少一个元素的列表?
关于如何从功能上思考和使非法国家无法代表的任何暗示?
谢谢!
如果我正确理解了您的问题,那么您正在寻找一种数据类型,该数据类型表示一个至少包含一个元素的列表。您可以使用以下内容定义自己的此类列表:
type NonEmptyList a = ListItem a (NonEmptyList a) | RootItem a
为了使生活更轻松,您可以定义一些辅助函数,以便可以与普通Elm相互转换List
:
toList : NonEmptyList a -> List a
toList list =
case list of
RootItem x -> [x]
ListItem x rest -> x :: toList rest
fromList : List a -> Maybe (NonEmptyList a)
fromList list =
case list of
[] -> Nothing
[x] -> Just (RootItem x)
(x::xs) -> Maybe.map (ListItem x) <| fromList xs
然后,您可以根据新的非空列表定义调色板。
type alias Palette =
{ bg : Color
, fg : NonEmptyList Color
}
现在fg
,编译器始终保证您的字段至少具有一个值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句