guix-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Learning the match-syntax...


From: Ricardo Wurmus
Subject: Re: Learning the match-syntax...
Date: Sat, 05 Jan 2019 23:35:23 +0100
User-agent: mu4e 1.0; emacs 26.1

Hi swedebugia,

> (define (metadata-ref file lookup)
>                       ^ 2 arguments
>   (fold (lambda (record acc)
>                   ^2 formals, why the acc?

“fold” is a higher order function that takes a two-argument procedure
(the lambda here), an initial value, and a list to fold over.

The procedure that is provided as the first argument is applied to each
element of the list *and* is given the current value of the
so-called accumulator (here bound to “acc”).

The accumulator first gets the initial value; in this case that’s #F.
The return value of the procedure is the new value of the accumulator.
The body is essentially just an “if” expression: the new value of the
accumulator is either whatever the “match” expression returns or it is
the unchanged value “acc”.

But nothing of this has anything to do with “match”.  Let’s look at the
match expressions.

>           (match record
>                  ^input
>             ((record key val)
>                ^match "record" "key" "val" in a list?

This is really destructuring the value of “record”, assuming that it is
a three element list, and binding each of the elements to a variable.
Try this:

--8<---------------cut here---------------start------------->8---
(use-modules (ice-9 match))
(match '(hello world how are you ?)
  ((greeting object . question)
   (length question)))
--8<---------------cut here---------------end--------------->8---

This will match the quoted expression against a pattern that binds a
list with at least two values to the variables “greeting”, “object”, and
“question” (for everything after the first two values).

>              (match val
>                        ^input
>                  (('list-pat . stuff) stuff)
>                      ^ if 'list-pat return stuff

If (eq? (car val) 'list-pat) then return (cdr val), even if that might
be the empty list.

>                  (('string-pat stuff) stuff)
>                      ^ if 'string-pat return stuff

This matches if “val” is a two element list where the car is
'string-pat.  It returns the cadr of “val” (cadr = car of the cdr).

>                  (('multiline-string stuff) stuff)

Similar here.

>                  (('dict records ...) records))
>                     ^if 'dict return first record

Close.  It returns all the values following 'dict.  This is the same as
if the pattern ('dict . records) had been used.

Hope this helps!

--
Ricardo




reply via email to

[Prev in Thread] Current Thread [Next in Thread]