Janet Notes and Examples

Functions

Functions have to be defined before they can be used. So your main goes at the bottom.

You can define functions inside of other functions, and can also create def’s and var’s in general inside of functions too, if you like.

As you’d expect, if you pass a mutable object to a function, you can mutate it inside the function and changes are seen by the caller.

# Variadic functions (taking a variable number of args).
(defn foo
  [a b & c]  # Extra args passed in are put into the `c` tuple.
  ...)

# Optional args.
(defn foo
  [a b &opt c d]  # `c` and `d` are optional (`nil` if not supplied)
  (default c 42)  # Give `c`
  (default d 86)  # and `d` a default value.
  ...)

# Ignore extra args.
(defn foo
  [a b &]  # Must pass at least two args.
  ...)

# Keyword-style args.
(defn foo
  [&keys {:size  size
          :color color
          :style style}]
  (pp size)
  (pp color)
  (pp style)
  ...)
# and call it like
(foo :size 8 :color "red" :style "retro")

# Note, if you prefer, you could pass in a struct and destructure like so:
(defn foo
  [{:size  size
    :color color
    :style style}]
  (pp size)
  (pp color)
  (pp style)
  ...)
# But then calling would look like:
(foo {:size 8 :color "red" :style "retro"})

Note that

  • some functions use the keyword-args style, while
  • other functions just take various args, and may at a brief glance appear to take keyword args, but actually don’t.
(foo :a 1 :b 2 :c 3)  # keyword args
(bar :unix "hey" 8)   # just various args

A quick read of the docstring should clarify any confusion.

Flags

A handful of functions take an optional “mode”, “mask”, or “flags” arg. This arg is a compact way to specify one or more flags from a set of possible flags, using a single keyword. For example, if the function foo can take the optional flags :a, :b, and :c, then you might call it like:

(foo "hey")       # no flags specified
(foo "hey" :a)    # just the `:a` flag
(foo "hey" :ab)   # `:a` and `:b` flags
(foo "hey" :ba)   # same as previous
(foo "hey" :abc)  # all three flags specified

Functions I’m aware of that use this pattern:

  • file/open
  • fiber/new
  • os/execute

Recall, Janet doesn’t have a built-in “set” type — the term “set” used above is in the generic sense.


Also supported:

  • destructuring
  • defn- for not-to-be-exported functions
  • varfn