2016-05-16 24 views
2

我试图按照Model the problem文章中的指导原则在Elm中创建调色板类型。我的第一个想法是说:需要帮助建模调色板类型

type alias Palette = List Color 

但这有缺点。调色板是一系列颜色,但它也必须有两种颜色,一种用于背景,一种用于前景。

我的第二次尝试是有一个记录类型:

type alias Palette = 
    { bg : Color 
    , fg : List Color 
    } 

这是更好,但我如何确保fg场有至少一个元素的列表?

任何提示如何功能考虑和make illegal states unrepresentable

谢谢!

回答

3

如果我正确理解你的问题,你正在寻找一个数据类型,表示一个至少包含一个元素的列表。

type NonEmptyList a = ListItem a (NonEmptyList a) | RootItem a 

为了使生活更轻松,那么你可以定义一些辅助功能,这样就可以转化为,并从正常榆树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场总是由编译器保证至少有一个值。