Monads/List monad: Difference between revisions
Content added Content deleted
(Added C++ implementation) |
(→{{header|F_Sharp|F#}}: Add true list monad implementation) |
||
Line 386: | Line 386: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
<lang fsharp> |
|||
type ListMonad() = |
|||
member o.Bind( (m:'a list), (f: 'a -> 'b list) ) = List.concat( List.map f m ) |
|||
member o.Return(x) = [x] |
|||
member o.Zero() = [] |
|||
let list = ListMonad() |
|||
let pyth_triples n = list { let! x = [1..n] |
|||
let! y = [x..n] |
|||
let! z = [y..n] |
|||
if x*x + y*y = z*z then return (x,y,z) } |
|||
printf "%A" (pyth_triples 100) |
|||
</lang> |
|||
(The original example, which follows, variously uses List.iter, a list comprehension and the Result type but doesn't define anything like a list monad.) |
|||
<lang fsharp> |
<lang fsharp> |
||
// Monads/List monad . Nigel Galloway: March 8th., 2021 |
// Monads/List monad . Nigel Galloway: March 8th., 2021 |
||
Line 408: | Line 426: | ||
Error: 10 is greater than 9 |
Error: 10 is greater than 9 |
||
</pre> |
</pre> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Factor comes with an implementation of Haskell-style monads in the <code>monads</code> vocabulary. |
Factor comes with an implementation of Haskell-style monads in the <code>monads</code> vocabulary. |