mirror of
https://github.com/correl/calrissian.git
synced 2024-11-23 11:09:58 +00:00
Add an error monad example to the README
This commit is contained in:
parent
de418111bb
commit
eec3555383
1 changed files with 46 additions and 5 deletions
51
README.rst
51
README.rst
|
@ -7,8 +7,9 @@ Introduction
|
|||
============
|
||||
|
||||
Calrissian is an implementation of monads in LFE, inspired by
|
||||
`erlando`_, mostly as a learning exercise. So far, only the Maybe and
|
||||
Identity monads are supported.
|
||||
`erlando`_, mostly as a learning exercise. So far, only the Maybe,
|
||||
Error and Identity monads are supported.
|
||||
|
||||
|
||||
Dependencies
|
||||
------------
|
||||
|
@ -44,10 +45,50 @@ And then do the usual:
|
|||
$ rebar compile
|
||||
|
||||
|
||||
Usage
|
||||
=====
|
||||
Examples
|
||||
========
|
||||
|
||||
Coming soon
|
||||
The following examples demonstrate some of the possible uses of monads
|
||||
in real-world code.
|
||||
|
||||
Error Monad
|
||||
-----------
|
||||
|
||||
The following is an example of using the error monad and do-notation
|
||||
to simplify flow control through a series of sequential operations
|
||||
that, if any step should fail, should halt execution and return an
|
||||
error.
|
||||
|
||||
The error monad will inspect the result of the previous operation. If
|
||||
it was successful (represented as ``'ok`` or ``(tuple 'ok result)``),
|
||||
the result will be passed on to the next operation. If it failed
|
||||
(represented as ``(tuple 'error reason)``, the error will be returned
|
||||
and execution will cease.
|
||||
|
||||
.. code:: scheme
|
||||
|
||||
(include-lib "deps/calrissian/include/monads.lfe")
|
||||
|
||||
(defun dostuff ()
|
||||
(do-m error-monad
|
||||
(input <- (fetch-input)) ;; fetch-input -> (tuple 'ok result) | (tuple 'error reason)
|
||||
(parsed <- (parse-input input)) ;; parse-input -> (tuple 'ok result) | (tuple 'error reason)
|
||||
(store-data parsed))) ;; store-data -> 'ok | (tuple 'error reason)
|
||||
|
||||
Without the error monad, the code might have looked like this:
|
||||
|
||||
.. code:: scheme
|
||||
|
||||
(defun dostuff ()
|
||||
(case (fetch-input)
|
||||
((tuple 'error reason)
|
||||
(tuple 'error reason))
|
||||
((tuple 'ok input)
|
||||
(case (parse-input input)
|
||||
((tuple 'error reason)
|
||||
(tuple 'error reason))
|
||||
((tuple 'ok parsed)
|
||||
(store-data parsed))))))
|
||||
|
||||
.. Links
|
||||
.. -----
|
||||
|
|
Loading…
Reference in a new issue