Skip to the content
Diaspar

08 / 10

Functions and labels

Arities, closures, and arguments passed by name.

A function takes values and gives one back: the value of the last form in its body. There is no return.

functions.dias
;; The last form of a body is what the function gives back.
(defn square [x]
  (* x x))

;; A function is a value: fn makes one without a name.
(def double (fn [x] (* x 2)))

;; It can be passed to a function, and given back by one.
(defn twice [f x]
  (f (f x)))

(defn adder [n]
  (fn [x] (+ x n)))

(defn main [args]
  (print (square 7) (double 21))
  (print (twice square 3) (twice double 3))
  (let [add-ten (adder 10)]
    (print (add-ten 5) (twice add-ten 5)))
  (print square))
Runs in your browser

Try it: Make a function that multiplies: (defn times [n] (fn [x] (* x n))), and pass (times 3) to twice.

A function is a value like a number is. fn makes one without a name. It can be passed to a function, given back by one, and kept in a collection. The function that adder gives back remembers the n it was made with.

More than one way to call it

A function may have several clauses, and the number of arguments picks one. A clause can call another, which is how a default is written by hand. & before the last parameter collects every argument that is left.

arities.dias
;; Several clauses: the number of arguments picks one.
(defn greet
  ([] (greet "stranger"))
  ([name] f"hello, {name}")
  ([name title] f"hello, {title} {name}"))

;; & takes whatever arguments are left, as a list.
(defn tally [label & numbers]
  f"{label}: {(count numbers)} numbers, {(sum numbers)} in all")

(defn main [args]
  (print (greet))
  (print (greet "Alvin"))
  (print (greet "Jeserac" "tutor"))
  (print (tally "scores" 3 4 5))
  (print (tally "nothing")))
Runs in your browser

Try it: Call (greet "a" "b" "c"). The report says how many arguments each clause takes.

Labels

Some arguments are better passed by name. A parameter written as a label with a value, width: 24, is one: the caller writes width: 40, or leaves it out and gets 24.

labels.dias
(use std.string)

;; width: and fill: are labels. Each has a default.
(defn banner [text width: 24 fill: "-"]
  (string.pad-center f" {text} " width fill: fill))

(defn main [args]
  (print (banner "Diaspar"))
  (print (banner "Diaspar" fill: "="))
  (print (banner "Diaspar" width: 40))

  ;; Labels go in any order, before or after the other arguments.
  (print (banner fill: "*" width: 16 "Lys")))
Runs in your browser

Try it: Add a label upper?: false to banner, and when it is true, pass the text through string.upper.

You have used labels since the first page: sep: of print, the fields of a record, when: in a pattern. They are one mechanism. A label is part of the call, not a value, so a label that the function does not have is an error.

unknown.dias
(use std.string)

(defn banner [text width: 24 fill: "-"]
  (string.pad-center f" {text} " width fill: fill))

(defn main [args]
  (print (banner "Diaspar" filler: "=")))
Runs in your browser

Try it: Take the report's advice.

Defaults are code

A default is an expression, evaluated at each call that leaves the label out. It may use the parameters before it.

defaults.dias
;; A default is an expression. It is evaluated at each call that leaves the
;; label out, and it may use the parameters before it.
(defn rect [width height: width label: f"{width} by {height}"]
  f"{label}, area {(* width height)}")

(defn main [args]
  (print (rect 3))
  (print (rect 3 height: 4))
  (print (rect 3 height: 4 label: "a door")))
Runs in your browser

Try it: Call (rect 3 label: "a tile"): the height still follows the width.

Since it is evaluated at each call, a default of #[] is a new empty vector every time. The trap that Python has, one list shared by every call, is not here.

Calls in a row

Calls nest, and a deep nest reads from the inside out. -> turns it around: it takes a value and passes it through a chain of calls, as the first argument of each.

pipeline.dias
(use std.string)

;; -> passes a value through a chain of calls, as each one's first argument.
(defn slug [title]
  (-> title
    (string.trim)
    (string.lower)
    (string.replace " " "-")))

(defn main [args]
  (print (slug "  The City and the Stars "))

  ;; The same, written inside out.
  (print (string.replace (string.lower (string.trim "  Against the Fall  ")) " " "-")))
Runs in your browser

Try it: Add a step to the chain that cuts the result to ten graphemes: (subs 0 10).

It is only a way of writing. (-> x (f a) (g b)) is (g (f x a) b), and the functions do not know the difference. Next: what happens when a function cannot give a value at all, errors.