-
Notifications
You must be signed in to change notification settings - Fork 147
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add basic lens functionality to standard library
- Loading branch information
Showing
2 changed files
with
71 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
let { Functor } = import! std.functor | ||
|
||
let { Applicative } = import! std.applicative | ||
|
||
let { Monoid, empty } = import! std.monoid | ||
|
||
let { (<>) } = import! std.semigroup | ||
|
||
type Const s a = { value : s } | ||
|
||
#[implicit] | ||
let functor : forall s . Functor (Const s) = { | ||
map = \f -> \c -> { value = c.value }, | ||
} | ||
|
||
#[implicit] | ||
let applicative : forall s . [Monoid s] -> Applicative (Const s) = { | ||
functor, | ||
apply = \f x -> { value = f.value <> x.value }, | ||
wrap = \_ -> { value = empty } | ||
} | ||
|
||
let app : s -> Const s a = \value -> { value } | ||
|
||
let run : Const s a -> s = \c -> c.value | ||
|
||
{ Const, functor, app, run } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
let { Functor, map } = import! std.functor | ||
let const @ { Const, ? } = import! std.functor.const | ||
let identity = import! std.identity | ||
|
||
|
||
type Lens s t a b = { app : forall f . [Functor f] -> (a -> f b) -> s -> f t } | ||
|
||
|
||
type Lens' s a = Lens s s a a | ||
|
||
|
||
let view lens x : Lens s t a b -> s -> a = | ||
let res = lens.app const.app x | ||
res.value | ||
|
||
|
||
let over lens f y : Lens s t a b -> (a -> b) -> s -> t = | ||
lens.app ?identity.functor (\x -> (f x)) y | ||
|
||
|
||
let set lens x : Lens s t a b -> b -> s -> t = over lens (\_ -> x) | ||
|
||
|
||
let make view set : (s -> a) -> (b -> s -> t) -> Lens s t a b = | ||
{ | ||
app = \k x -> map (\y -> set y x) (k (view x)), | ||
} | ||
|
||
|
||
#[infix(right, 8)] | ||
let (^) g f : Lens j k s t -> Lens s t a b -> Lens j k a b = { | ||
app = \k -> g.app (f.app k), | ||
} | ||
|
||
|
||
#[infix(left, 1)] | ||
let (&) x g : a -> (a -> b) -> b = g x | ||
|
||
|
||
#[infix(right, 9)] | ||
let (^.) x lens : s -> Lens s t a b -> a = view lens x | ||
|
||
|
||
{ Lens, Lens', view, set, over, make, (^), (&), (^.) } |