Skip to content

Instantly share code, notes, and snippets.

@DrBoolean
Created January 7, 2016 21:04
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrBoolean/d8cec62d495be6afb605 to your computer and use it in GitHub Desktop.
Save DrBoolean/d8cec62d495be6afb605 to your computer and use it in GitHub Desktop.
State Monad is useful example
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>
@DrBoolean
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment