Skip to content

Instantly share code, notes, and snippets.

@wraikny
Last active July 28, 2019 11:25
Show Gist options
  • Save wraikny/a32049a274831b527c7935e1dd096d06 to your computer and use it in GitHub Desktop.
Save wraikny/a32049a274831b527c7935e1dd096d06 to your computer and use it in GitHub Desktop.
type Model =
{
count : int
log : int list
}
// Input Kind
type Msg = Add of int | Undo
// define function
// The type is inferred as (Msg -> Model -> Model)
let update msg model =
match msg with
| Add i ->
{
count = model.count + i
// stack old count
log = model.count :: model.log
}
| Undo ->
// pop stack
match model.log with
| [] -> model
| x :: xs -> { count = x; log = xs }
// define first model
// The type is inferred as Model
let initModel = { count = 0; log = [] }
// The type is inferred as Model list list
let msgsList =
[
[]
[ Add 10]
[ Add 10; Add 15; Undo; Add -1 ]
[ 1..10 ] |> List.map(fun x -> if x % 3 = 0 then Undo else Add x)
]
// The type is inferred as seq<Model>
let models =
msgsList
|> Seq.map (fun msgs ->
msgs
|> Seq.map update
|> Seq.fold (|>) initModel
(*
// same to
initModel
|> update msgs.[1]
|> update msgs.[2]
...
|> update msgs.[n]
*)
)
models
|> Seq.map (sprintf "%A")
|> String.concat "\n\n"
|> fun x ->
printfn "--- Results ---"
printfn "%s" x
printfn "---------------"
(*
--- Results ---
{count = 0;
log = [];}
{count = 10;
log = [0];}
{count = 9;
log = [10; 0];}
{count = 22;
log = [12; 5; 1; 0];}
---------------
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment