Monads/Writer monad: Difference between revisions

Content added Content deleted
(J draft)
Line 10: Line 10:
# Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
# Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)



=={{header|J}}==

Based on javascript implementation:

<lang J>root=: %:
incr=: >:
half=: -:

tostr=: ,@":

loggingVersion=: conjunction define
n;~u
)

Lroot=: root loggingVersion 'obtained square root'
Lincr=: incr loggingVersion 'added 1'
Lhalf=: half loggingVersion 'divided by 2'

loggingUnit=: verb define
y;'Initial value: ',tostr y
)

loggingBind=: adverb define
r=. u 0{::y
v=. 0{:: r
v;(1{::y),LF,(1{::r),' -> ',tostr v
)

loggingCompose=: dyad define
;(dyad def '<x`:6 loggingBind;y')/x,<loggingUnit y
)</lang>

Task example:

<lang J> 0{::Lhalf`Lincr`Lroot loggingCompose 5
1.61803
1{::Lhalf`Lincr`Lroot loggingCompose 5
Initial value: 5
obtained square root -> 2.23607
added 1 -> 3.23607
divided by 2 -> 1.61803</lang>


=={{header|JavaScript}}==
=={{header|JavaScript}}==