Skip to content

Instantly share code, notes, and snippets.

@EugeneN
Created December 6, 2012 15:29
Show Gist options
  • Save EugeneN/4225334 to your computer and use it in GitHub Desktop.
Save EugeneN/4225334 to your computer and use it in GitHub Desktop.
Currency monad
# mv = [currency amount]
# v = "$ 123"
rates =
'$': 8
'E': 10
'R': 0.25
'U': 1
'T': 123
unit = (mv) ->
"#{mv[0]} #{(mv[1] / rates[mv[0]]).toFixed 2}"
bind = (mv, f) ->
[currency, amount] = mv
if currency in (Object.keys rates) and amount and not (isNaN amount)
f (rates[currency] * (parseInt amount, 10))
else
"Bad value"
lift_value = (v) ->
v.split ' '
lift2 = (f) ->
(a, b, res_curr) ->
ma = lift_value a
mb = lift_value b
bind(ma, (a) ->
bind(mb, (b) ->
unit([res_curr, f(a, b)])))
add = (a, b) -> a + b
sub = (a, b) -> a - b
cadd = lift2 add
csub = lift2 sub
doasync = (funcs...) ->
module.exports = {unit, bind, lift2, add, cadd, csub}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment