Skip to the content
Diaspar

10 / 10

Effects

A function asks; whoever called it decides the answer.

Some things a function cannot decide by itself: where a log line goes, what time it is, what to do about a bad value. An effect is how it asks. The function performs the effect, and whoever called it decides the answer.

log.dias
;; An effect is a request a function makes without knowing who answers.
(defeffect Log [message])

(defn launch [ship]
  (perform (Log f"checking {ship}"))
  (perform (Log f"{ship} is away"))
  :launched)

(defn main [args]
  ;; This caller prints every message.
  (print (handle (launch "Seeker")
           (Log message) [resume] (do (print "log:" message)
                                      (resume nil))))

  ;; This one wants silence. launch is the same function.
  (print (handle (launch "Seeker")
           (Log _) [resume] (resume nil))))
Runs in your browser

Try it: Give launch a third perform. Both callers follow, and neither was changed.

defeffect declares an effect, with fields like a record. perform makes the request. handle runs a form, and its clauses say what to do with each request the form makes: a pattern for the effect, a name for the way back, then the answer. (resume nil) goes back into launch, right where it stopped.

launch was written once. One caller prints its messages and the other drops them, and launch has no parameter for either.

A request has an answer

What a handler passes to resume is what perform gives back. So an effect is also a question.

ask.dias
;; perform gives back what the handler passes to resume.
(defeffect Ask [question])

(defn boarding-pass []
  (let [name (perform (Ask "name"))
        seat (perform (Ask "seat"))]
    f"{name}, seat {seat}"))

(defn main [args]
  ;; The answers come from the caller: a form, a file, a test.
  (print (handle (boarding-pass)
           (Ask "name") [resume] (resume "Alvin")
           (Ask "seat") [resume] (resume 12)))

  ;; A handler is found by pattern: this one answers every question alike.
  (print (handle (boarding-pass)
           (Ask question) [resume] (resume (str "<" question ">")))))
Runs in your browser

Try it: Remove the clause for "seat" from the first handler. Nobody answers that question, and the report says so.

A handler is found by pattern, like a clause of match. The first handler has an answer for each question. The second answers any question the same way.

unhandled.dias
(defeffect Ask [question])

(defn boarding-pass []
  (let [name (perform (Ask "name"))]
    f"{name}, welcome aboard"))

(defn main [args]
  (print (boarding-pass)))
Runs in your browser

Try it: Handle it in main, as the report suggests.

The world is a handler

A function that needs the time performs an effect for it. In a program, the handler asks the clock. In a test, it gives whatever hour the test is about.

clock.dias
(defeffect Now [])

(defn greeting [name]
  (let [hour (perform (Now))]
    (cond
      (< hour 12) f"good morning, {name}"
      (< hour 18) f"good afternoon, {name}"
      :else f"good evening, {name}")))

;; A test gives the function any hour it likes. Nothing is mocked: the
;; function never had a clock of its own.
(defn at [hour f]
  (handle (f)
    (Now) [resume] (resume hour)))

(defn main [args]
  (print (at 9 (fn [] (greeting "Alvin"))))
  (print (at 15 (fn [] (greeting "Alvin"))))
  (print (at 22 (fn [] (greeting "Alvin")))))
Runs in your browser

Try it: Add a fourth greeting, for the hours before six, and a call that shows it.

Nothing was mocked or injected. greeting never had a clock of its own to replace: it only ever asked. The same goes for files, the network, and random numbers.

Not going back

A handler does not have to resume. If it gives a value instead, the work that performed the effect is abandoned, and handle gives that value.

stop.dias
(defeffect Found [item])

;; Looks at every element, and announces each one it likes.
(defn search [items wanted?]
  (for [item items]
    (when (wanted? item)
      (perform (Found item))))
  :nothing-found)

(defn main [args]
  ;; A handler that does not resume ends the work: handle gives its value.
  (print (handle (search #[3 8 12 5 20] (fn [n] (> n 10)))
           (Found item) [_] f"stopped at {item}"))

  (print (handle (search #[3 8 5] (fn [n] (> n 10)))
           (Found item) [_] f"stopped at {item}")))
Runs in your browser

Try it: Change the test to (> n 4). The search stops at the first match and never looks at the rest.

An error is an effect

Now the errors of the last page can be said in one line: error performs an effect named Fail, and catch is a handler that does not resume. A handler that does resume can do what catch cannot: give the failed call a value and let the work go on.

fail.dias
(defn parse-port [text]
  (if (= text "8080")
    8080
    (error f"not a port: {text}")))

(defn ports [texts]
  (for [text texts] (parse-port text)))

(defn main [args]
  ;; An error is an effect named Fail. catch is a handler that does not
  ;; resume.
  (print (catch (ports #["8080" "eighty" "8080"])
           e "gave up"))

  ;; A handler may resume instead: the failed call gets a value, and the work
  ;; goes on from where it failed.
  (print (handle (ports #["8080" "eighty" "8080"])
           (Fail f) [resume] (resume 0))))
Runs in your browser

Try it: Resume with nil instead of 0, and the bad port becomes a gap in the list.

The decision is made at the top, by the caller who knows what a bad port should mean. It is carried out at the bottom, in the middle of the loop, without the loop knowing.

One limit on this page: a handler here resumes as the last thing it does, or not at all. A handler that keeps resume for later, which is what generators and tasks are made of, needs a second stack to keep the paused work on. The native diaspar has that, and the build that runs in your browser does not yet.