Last active
November 28, 2016 14:05
-
-
Save theor/0f3cbae332da0a6cdf47 to your computer and use it in GitHub Desktop.
Redux.Net counter sample in f#, with a couple of helper types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// needs the redux.net nuget package | |
#r "PresentationCore.dll" | |
#r "PresentationFramework.dll" | |
#r "../packages/Redux.NET.0.2.0/lib/portable-net45+netcore45/Redux.dll" | |
#r "System.Core.dll" | |
#r "System.dll" | |
#r "../packages/Rx-Core.2.2.5/lib/net45/System.Reactive.Core.dll" | |
#r "../packages/Rx-Interfaces.2.2.5/lib/net45/System.Reactive.Interfaces.dll" | |
#r "../packages/Rx-Linq.2.2.5/lib/net45/System.Reactive.Linq.dll" | |
#r "../packages/Rx-PlatformServices.2.2.5/lib/net45/System.Reactive.PlatformServices.dll" | |
#r "System.Xaml.dll" | |
#r "UIAutomationTypes.dll" | |
#r "WindowsBase.dll" | |
// F# boilerplate | |
/// A Redux IAction containing a value - intended for discriminated unions | |
type FAction<'a>(value) = | |
member val Value: 'a = value | |
interface Redux.IAction | |
/// Takes a F# function and return a wrapped Func applying this function to the FAction Value | |
let reducerBoilerplate (reducer:'a->'b->'a) : System.Func<'a,#Redux.IAction,'a> = | |
let inner state (action:Redux.IAction) = | |
match action with | |
| :? FAction<_> as faction -> reducer state faction.Value | |
| _ -> state | |
System.Func<_,_,_>(inner) | |
// View (could use FsXaml instead, done by hand for brevity) | |
open System | |
open System.Windows | |
open System.Windows.Controls | |
type CounterWindow() as this = | |
inherit Window() | |
let tb = TextBlock() | |
let badd = Button() | |
let bsub = Button() | |
do | |
let sp = StackPanel() | |
this.Content <- sp | |
sp.Children.Add tb |> ignore | |
badd.Content <- "+" | |
sp.Children.Add badd |> ignore | |
bsub.Content <- "-" | |
sp.Children.Add bsub |> ignore | |
member this.CounterRun:TextBlock = tb | |
member this.AddButton:Button = badd | |
member this.SubButton:Button = bsub | |
// Action and reducer | |
type CounterAction = Inc | Dec | |
let reducer state value = | |
match value with | |
| Inc -> state + 1 | |
| Dec -> state - 1 | |
[<EntryPoint>] | |
[<STAThread>] | |
let main argv = | |
let store = Redux.Store(0, reducerBoilerplate reducer) | |
let w = CounterWindow() | |
// View-action wiring | |
store.Add(fun i -> w.CounterRun.Text <- i.ToString()) | |
w.AddButton.Click.Add (fun _ -> FAction Inc |> store.Dispatch) | |
w.SubButton.Click.Add (fun _ -> FAction Dec |> store.Dispatch) | |
let app = new Application() | |
app.Run(w) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment