2016-05-16 23 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場總是由編譯器保證至少有一個值。