Created
January 7, 2016 21:04
-
-
Save DrBoolean/d8cec62d495be6afb605 to your computer and use it in GitHub Desktop.
State Monad is useful example
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
import State, {get, put, modify} from 'fantasy-states' | |
import {prop, compose, map, chain, merge, always} from 'ramda' | |
// Unfortunately Binary Gendered Baby Page | |
//========================================== | |
const babies = [{id: 2, name: 'Anjali', sex: 'F'}, {id: 3, name: 'Antonio', sex: 'M'}] | |
// isFemale :: Baby -> Bool | |
const isFemale = b => b.sex === 'F' | |
// findBaby :: Int -> Baby | |
const findBaby = i => babies[i] | |
// updatePrefs :: Baby -> State Prefs Baby | |
const updatePrefs = b => modify(merge({bgColor: isFemale(b) ? 'pink' : 'blue'})).map(always(b)) | |
// html :: Baby -> Prefs -> Html | |
const html = (b, prefs) => `<div style={background-color: ${prefs.bgColor}, font: ${prefs.font} }>${b.name}</div>` | |
// drawPage :: Baby -> State Prefs Html | |
const drawPage = b => get.map(prefs => html(b, prefs)) | |
// app :: State Int Html | |
const app = compose(chain(drawPage), chain(updatePrefs), map(findBaby)) | |
app(State.of(0)).evalState({font: 'cursive'}) | |
// <div style={background-color: pink, font: cursive }>Anjali</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple example of how state can be used in a helpful way. Not as pretty as haskell or purescript since we don't have
>>
or for comprehensions, but it still works fine.