更新模型时应用Maybes

时间:2017-08-13 10:09:54

标签: elm

我想以这种方式更新我的模型:

updatedModel =
  if model.firstChord && model.secondChord then
    { model | firstChord = {}, secondChord = {} }
  else
    model

firstChord和secondChord都属于Chord类型:

type alias Chord =
{   root : Maybe Pitch
,   third : Maybe Pitch
,   fifth : Maybe Pitch
}

音高类型如下:

-- pitch
type alias Pitch = ( PitchName, PitchLevel )

-- pitch name
type alias PitchName = String

-- pitch level
type alias PitchLevel = Int

我的初始模型包含以下字段:

{ firstChord =
    {   root = ( "C", 3 )
    ,   third = ( "E", 3 )
    ,   fifth = ( "G", 3 )
    }
, secondChord =
    {   root = ( "F", 3 )
    ,   third = ( "A", 3 )
    ,   fifth = ( "C", 4 )
    }

我喜欢有可选的音高值。

如何更新我的模型给它一个值或什么都没有?

感谢。

2 个答案:

答案 0 :(得分:3)

不太确定你在寻找什么。我邀请你想要一个像这样的可能和弦。

type Pitch =
    Pitch String Int

type alias Chord =
    { root: Maybe Pitch
    , third: Maybe Pitch
    , fifth: Maybe Pitch
    }

type alias Model =
    { firstChord: Maybe Chord
    , secondChord: Maybe Chord
    }

init: Model
init =
    { firstChord =
        { root = Pitch "C" 3
        , third = Pitch "E" 3
        , fifth = Pitch  "G" 3
        }
    , secondChord =
        { root = Pitch "F" 3
        , third = Pitch "A" 3
        , fifth = Pitch "C" 4
        }
    }

update: Model -> Model
update model =
    case (model.firstChord, model.secondChord) of
        (Just first, Just second) ->
            { model | firstChord = Nothing, secondChord = Nothing}
        _ ->
            model

答案 1 :(得分:0)

当您拥有Maybe a类型时,例如Maybe Pitch,您可以通过两种方式设置其值:NothingJust a。所以不要这样:

{ firstChord =
    {   root = ( "C", 3 )
    ,   third = ( "E", 3 )
    ,   fifth = ( "G", 3 )
    }
, secondChord =
    {   root = ( "F", 3 )
    ,   third = ( "A", 3 )
    ,   fifth = ( "C", 4 )
    }

......你需要这样做:

{ firstChord =
    {   root = Just ( "C", 3 )
    ,   third = Just ( "E", 3 )
    ,   fifth = Just ( "G", 3 )
    }
, secondChord =
    {   root = Just ( "F", 3 )
    ,   third = Just ( "A", 3 )
    ,   fifth = Just ( "C", 4 )
    }

当然,您然后使用Nothing,因此请注明没有值:

firstChord =
    {   root = Just ( "C", 3 )
    ,   third = Just ( "E", 3 )
    ,   fifth = Nothing
    }