JanetDocsPlaygroundI'm feeling luckyGitHub sign in

match



    macro
    boot.janet on line 1733, column 1

    (match x & cases)

    Pattern matching. Match an expression `x` against any number of 
    cases. Each case is a pattern to match against, followed by an 
    expression to evaluate to if that case is matched. Legal patterns 
    are:

    * symbol -- a pattern that is a symbol will match anything, binding 
      `x`'s value to that symbol.

    * array or bracket tuple -- an array or bracket tuple will match 
      only if all of its elements match the corresponding elements in 
      `x`. Use `& rest` at the end of an array or bracketed tuple to 
      bind all remaining values to `rest`.

    * table or struct -- a table or struct will match if all values 
      match with the corresponding values in `x`.

    * tuple -- a tuple pattern will match if its first element matches, 
      and the following elements are treated as predicates and are 
      true.

    * `_` symbol -- the last special case is the `_` symbol, which is a 
      wildcard that will match any value without creating a binding.

    While a symbol pattern will ordinarily match any value, the pattern 
    `(@ <sym>)`, where <sym> is any symbol, will attempt to match `x` 
    against a value already bound to `<sym>`, rather than matching and 
    rebinding it.

    Any other value pattern will only match if it is equal to `x`. 
    Quoting a pattern with `'` will also treat the value as a literal 
    value to match against.


See also:case3 examplesSign in to add an example
Loading...
# demo of (@ <sym>) feature
(let [content "# => label"]
  (match [:comment @{} "# => label"]
    [:comment _ (@ content)]
    :found
    nil))
# => :found
sogaiuPlayground
# complex matching, when you need to use predicates
# to determine a match
(def test {:a {:b 1} :c 2})
(match test
  ({:a a} (dictionary? a)) (print "is a dictionary"))
# --> "is a dictionary"

(match test
  ({:a a} (boolean? a)) (print "is a dictionary"))
# --> nil
llmIIPlayground
(def a-tuple-1 [:number 10])
(def a-tuple-2 [:string "Hello there!"])
(defn show [what]
  (match what
    [:number n] (printf "It's a number! %d" n)
    [:string s] (printf "Here's a string: %s" s)
    _ (printf "I dunno what this is: %q" what)))

(show a-tuple-1)
(show a-tuple-2)
(show [:array @[]])
roobiePlayground