Monads: Difference between revisions

Added a Ruby Section with a List Monad subsection
m (→‎{{header|Clojure}}: remove colons from subsection headers in Clojure section)
(Added a Ruby Section with a List Monad subsection)
Line 51:
 
That said J does not, by default, implicitly choose function implementation (which is probably what was implied in this context). But let's wait for the task description to explicitly call for that before trying to address that issue...
 
=={{header|Ruby}}==
 
===List Monad===
 
<lang ruby>
class Array
def bind(f)
map(&f).reduce(:concat)
end
def self.unit(*args)
args
end
end
 
inc = -> e { Array.unit(e + 1) }
str = -> e { Array.unit(e.to_s) }
 
Array.unit(3,4,5).bind(inc).bind(str) #=> ["4", "5", "6"]
 
# Note that inc and str cannot be composed directly,
# as they don't have compatible type signature.
# Due to duck typing (Ruby will happily turn arrays into strings),
# in order to show this, a new function will have to be used:
 
doub = -> n {[2*n]}
[3,4,5].bind(inc).bind(doub) #=> [8, 10, 12]
 
# Direct composition will cause a TypeError, as Ruby cannot evaluate 2*[4, 5, 6]
comp = -> f, g {-> x {f[g[x]]}}
[3,4,5].bind(comp[doub, inc]) #=> TypeError: Array can't be coerced into Fixnum
 
# Composition needs to be defined in terms of bind
class Array
def bind_comp(f, g)
bind(g).bind(f)
end
end
 
[3,4,5].bind_comp(doub, inc) #=> [8, 10, 12]
</lang>
Anonymous user