On this page:
prism?
prism/  c
make-prism
prism-match
prism-cast
success-prism
failure-prism
8.12

2 Prisms🔗ℹ

 (require glass/prism) package: glass

A prism is a type of optic for focusing on a specific kind of subject and ignoring other kinds. A prism is built from a matching function, which focuses on subjects of the correct kind, and a casting function, which transforms a replacement focus back into the subject.

procedure

(prism? v)  boolean?

  v : any/c
A predicate for prisms.

procedure

(prism/c subject-contract focus-contract)  contract?

  subject-contract : contract?
  focus-contract : contract?
A contract combinator for prisms. Creates a contract that accepts prisms whose subjects are checked with subject-contract and whose foci are checked with focus-contract.

procedure

(make-prism matcher caster [#:name name])  prism?

  matcher : (-> any/c option?)
  caster : (-> any/c any/c)
  name : (or/c interned-symbol? #f) = #f
Constructs a prism named name.

Examples:
(define number-string-prism
  (make-prism
   (λ (s)
     (define num (string->number s))
     (if num (present num) absent))
   number->string
   #:name 'number-string-prism))

 

> (prism-match number-string-prism "124")

(present 124)

> (prism-match number-string-prism "elephant")

#<absent>

> (prism-cast number-string-prism 100)

"100"

procedure

(prism-match prism subject)  option?

  prism : prism?
  subject : any/c
Matches subject against prism, returning an option that is present if prism was able to extract a focus from subject and absent otherwise.

Examples:
> (prism-match success-prism (success 123))

(present 123)

> (prism-match success-prism (failure "oh no!"))

#<absent>

procedure

(prism-cast prism focus)  any/c

  prism : prism?
  focus : any/c
Casts focus back into a subject value using prism. This is the inverse operation of prism-match if prism-match successfully extracts a value from a subject, that value can be converted back to the original subject using prism-cast.

Example:
> (prism-cast success-prism 123)

(success 123)

Two prisms which focus on successful and failed result values, respectively.

Examples:
> (prism-match success-prism (failure "kaboom!"))

#<absent>

> (prism-match failure-prism (failure "kaboom!"))

(present "kaboom!")

> (prism-cast failure-prism "kaboom!")

(failure "kaboom!")