Skip to content

Instantly share code, notes, and snippets.

@ebiggs
ebiggs / Maybe.coffee
Last active June 20, 2016 04:32
CoffeeScript Maybe Monad - couldn't find one with a Google search so I had to roll my own, hopefully this one showed up for yours ;) Good code coverage in the jasmine spec, so feel confident using it with reckless abandon ;) Maybe.coffee was definitely built with Some(coffea arabica) in my veins ;)
###
Like java, javascript is optimized for throwing null pointer exceptions
coffeescript helps with its series of ? operators
but here is a scala option-eqsue "maybe monad" when such semantics
are preferred over the ? operators or when you want your data
to self-document its indefinite-ness (regular vars don't warn you
that you may get null or undefined!).
note that we're perfectly happy to give you a Some(null) or a Some(undefined)
just like scala. if you have an x that you want to fmap to None if it's
@ebiggs
ebiggs / iomonad.coffee
Last active December 12, 2015 04:28
basic IO Monad in coffeescript
IO = (f) ->
ioF = -> f()
ioF.bind = (getsNextIoF) -> IOChain(ioF, getsNextIoF)
ioF
IOChain = (ioF, getNextIoF) ->
ioCF = ->
value = ioF()
nextIoF = getNextIoF(value)
nextIoF()
@ebiggs
ebiggs / flatmaplove.md
Last active December 12, 2015 07:08
Feeling the love for flatMap lately...

Been really loving flatMap lately. I used to mostly regard it for its usefulness in its relationship to scala's for comprehensions but I'm now kind of loving it for its use as a "subtractive" and "additive" map. What I mean is that when working with Sequences you can flatMap to Seq() to get rid of something or to a Seq( ... ) if you want to split something into multiple things. Basically flatten its inherent composition. Here's a lil gist illustrating the idiom. The idea is you have a sequence of Good ('G), Neutral ('N), and Bad ('B) vibes. After the party the bad vibes are gone and the good vibes have doubled, leaving the neutral vibes unchanged. The party1 function illustrates a more linear way of thinking about the party and party2 represents some flatMap magic :). Personally I think party2, though more verbose, represents a clearer reflection of the process. It seems a bit more illustrative/declarative of what the point of the party is. The result of Party2 also has a nicer order to it.

scala> v
@ebiggs
ebiggs / iomonad.coffee
Created February 16, 2013 17:23
io monad redux
IO = (doFirst) ->
io = () -> doFirst()
io.bind = (f) -> IO(-> f(doFirst())())
io
ioAlert = (x) -> IO(-> alert(x))
ioConfirm = (x) -> IO(-> confirm(x))
ioPrompt = (x) -> IO(-> prompt(x))
main = ->
@ebiggs
ebiggs / bincomp.md
Last active December 13, 2015 21:58
Composing composition in haskell (.).(.) is an interesting and surprisingly useful thing! But how can we compute it ourselves?

##Composing Composition.

When using curried binary operators like + and - we can't compose with (.) because (.) has the wrong signature:

(.) :: (b -> c) -> (a -> b) -> a -> c

as such the expression