Skip to content

Commit

Permalink
initial
Browse files Browse the repository at this point in the history
  • Loading branch information
hellerve committed Oct 28, 2019
0 parents commit 613334a
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 0 deletions.
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# lens

*Early WIP, also includes an implementation for Prisms on Maybes only*

A simple Lens library for Carp.

## Usage

```clojure
(load "[email protected]:hellerve/lens.carp@master")

(deftype Address [city String street (Pair String Int)])

(defn main []
(let-do [addr (Lens.for Address street)
stre (Lens.for Pair a)
comp (Lens.compose &addr &stre)
data (Address.init @"Berlin" (Street.init 10 @"Paul-Lincke-Ufer"))]
(println* &(~(Lens.get &comp) &data))
(println* &(~(Lens.set &comp) @&data @"no"))
(println* &(Lens.over &comp @&data &(fn [a] (reverse &a))))
)
)
```

<hr/>

Have fun!
14 changes: 14 additions & 0 deletions examples/simple.carp
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
(load "lens.carp")

(deftype Address [city String street (Pair String Int)])

(defn main []
(let-do [addr (Lens.for Address street)
stre (Lens.for Pair a)
comp (Lens.compose &addr &stre)
data (Address.init @"Berlin" (Pair.init @"Paul-Lincke-Ufer" 10))]
(println* &(~(Lens.get &comp) &data))
(println* &(~(Lens.set &comp) @&data @"no"))
(println* &(Lens.over &comp @&data &(fn [a] (reverse &a))))
)
)
58 changes: 58 additions & 0 deletions lens.carp
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
(deftype (Lens a b) [
get (Fn [&a] b)
set (Fn [a b] a)
])

; should be f a b and work with higher orders, but oh well
(deftype (Prism a b) [
get (Fn [&a] (Maybe b))
set (Fn [a b] a)
])

(defmodule Lens
(defn compose [ab bc]
(Lens.init
(fn [a] (~(get bc) &(~(get ab) a)))
(fn [a c]
(let [inner (~(set bc) (~(get ab) &a) c)]
(~(set ab) a inner)))))

(defn over [l p f]
(let [transformed (~f (~(get l) &p))]
(~(set l) p transformed)))

(defn to-prism [l]
(Prism.init
(fn [a] (Maybe.Just (~(get l) a)))
@(set l)))

(defndynamic for- [t el]
(list 'Lens.init
(list 'fn ['a] (list 'copy (list (Symbol.prefix t el) 'a)))
(Symbol.prefix t (Symbol.join ['set- el]))))

(defmacro for [t el]
(Lens.for- t el))
)

(defmodule Prism
(defn compose [ab bc]
(Prism.init
(fn [a]
(match (~(get ab) a)
(Maybe.Nothing) (Maybe.Nothing)
(Maybe.Just b) (~(get bc) &b)))
(fn [a c]
(match (~(get ab) &a)
(Maybe.Nothing) a
(Maybe.Just b)
(let [inner (~(set bc) b c)]
(~(set ab) a inner))))))

(defn over [l p f]
(match (~(get l) &p)
(Maybe.Nothing) p
(Maybe.Just a)
(let [transformed (~f a)]
(~(set l) p transformed))))
)

0 comments on commit 613334a

Please sign in to comment.