aboutsummaryrefslogtreecommitdiff
path: root/doc/ref/general/lens.texi
blob: 144478c3500b99cb97c22cdb86fd05e12e073b71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@node Lenses
@section Lenses

Provided by the module @code{(hnh util lens)}

A lens system for Scheme. All these procedures are pure. In general,
procedures fetching values from objects return that value, while
procedures ``setting'' or ``mutating'' objects returns a new instance
of the object, with the field in question replaced.

Lenses aren't a special type, but rather procedures which return a
value when called with one argument, and produce a new container with
an updated value when called with two arguments.

For example, the lens to focus the first element of a pair is
implemented as:

@lisp
(define car*
  (case-lambda ((pair) (car pair))
               ((pair value) (cons value (cdr pair)))))
@end lisp

@defun compose-lenses lenses ...
@defunx lens-compose lenses ...
Creates a new lens, which is the compound from all the given lenses.

Lenses composes left to right, so earlier lenses in @var{lenses} are
applied earlier.
@end defun

@defmac get object lenses ...
Do a deep lookup. Lenses are composed as per @code{compose-lenses}.
@end defmac

@defmac set object lenses ... value
Do a deep update of a field, and return a new object with the focused
element replaced. Lenses are composed as per @code{compose-lenses}.
@end defmac

@defun modify object lens f args ...
Returns a new object, with the value focused by @var{lens} replaced by
the result of calling @var{f}, with the old value, and the extra
arguments given.
@end defun

@defmac modify* object lens ... f
Like @code{modify}, but auto compose lenses, and don't allow extra
arguments to @var{f}.
@end defmac

@defmac build-lens getter setter
Where any of getter or setter can either be a single symbol, or a list.
@end defmac

@deftp {Scheme Lens} identity-lens
A lens focusing the given object. Showing the value returns the root
value, and setting the value just returns the new value.
@end deftp

@deftp {Scheme Lens} ref idx
Focuses the element at index @var{idx} in a list.
@end deftp

@deftp {Scheme Lens} car*
@deftpx {Scheme Lens} cdr*
Focuses the first or second element of a pair.
@end deftp

@defun each object lens proc
@end defun