Monads/List monad: Difference between revisions
Content added Content deleted
(+Racket) |
|||
Line 484: | Line 484: | ||
{{trans|JavaScript}} |
{{trans|JavaScript}} |
||
=== Vanilla Racket === |
|||
Note that this also demonstrates how to use Racket's macro system to implement the do syntax. |
Note that this also demonstrates how to use Racket's macro system to implement the do syntax. |
||
Line 529: | Line 531: | ||
(pythagorean-triples* 25) |
(pythagorean-triples* 25) |
||
;; => '((3 4 5) (5 12 13) (6 8 10) (8 15 17) (9 12 15) (12 16 20))</lang> |
|||
=== With functional package === |
|||
The [https://docs.racket-lang.org/functional/interfaces.html functional] package has already implemented the list monad. |
|||
<lang racket>#lang racket |
|||
(require data/monad |
|||
data/applicative) |
|||
(define (pythagorean-triples n) |
|||
(sequence->list |
|||
(do [x <- (range 1 n)] |
|||
[y <- (range (add1 x) n)] |
|||
[z <- (range (add1 y) n)] |
|||
(if (= (+ (* x x) (* y y)) (* z z)) |
|||
(pure (list x y z)) |
|||
'())))) |
|||
(pythagorean-triples 25) |
|||
;; => '((3 4 5) (5 12 13) (6 8 10) (8 15 17) (9 12 15) (12 16 20))</lang> |
;; => '((3 4 5) (5 12 13) (6 8 10) (8 15 17) (9 12 15) (12 16 20))</lang> |
||