arturopala / elm-monocle / Monocle.Lens

A Lens is a functional concept which solves a very common problem: how to easily update a complex immutable structure, for this purpose Lens acts as a zoom into a record.

Definition


type alias Lens a b =
{ get : a -> b, set : b -> a -> a }

In order to create Lens we need to supply 2 functions: set and get

Example

addressStreetNameLens : Lens Address String
addressStreetNameLens =
    let
        get a =
            a.streetName

        set sn a =
            { a | streetName = sn }
    in
    Lens get set

placeAddressLens : Lens Place Address
placeAddressLens =
    let
        get p =
            p.address

        set a p =
            { p | address = a }
    in
    Lens get set

placeStreetName : Lens Place String
placeStreetName =
    compose placeAddressLens addressStreetNameLens

Derived methods

compose : Lens a b -> Lens b c -> Lens a c

Composes Lens a b with Lens b c and returns Lens a c

modify : Lens a b -> (b -> b) -> a -> a

Modifies given function (b -> b) to be (a -> a) using Lens a b

addressStreetNameLens = Lens Address String
fx streetName = String.reverse streeName
fx2 = Lens.modify addressStreetNameLens fx
fx2 {streetName="abcdef"} == {streetName="fedcba"}

modify2 : Lens a b -> Lens c d -> (( b, d ) -> ( b, d )) -> ( a, c ) -> ( a, c )

Modifies given function (b,d) -> (b,d) to be (a,c) -> (a,c) using Lens a b and Lens c d

modify3 : Lens a b -> Lens c d -> Lens e f -> (( b, d, f ) -> ( b, d, f )) -> ( a, c, e ) -> ( a, c, e )

Modifies given function (b,d,f) -> (b,d,f) to be (a,c,e) -> (a,c,e) using Lens a b and Lens c d and Lens e f

modifyAndMerge : Lens a b -> (b -> ( b, c )) -> (c -> c -> c) -> ( a, c ) -> ( a, c )

Modifies given function (b -> (b,c)) to be (a,c) -> (a,c) using Lens a b and merge function

zip : Lens a c -> Lens b d -> Lens ( a, b ) ( c, d )

Zips Lens a c with Lens b d to form Lens ( a, b ) ( c, d )

tuple : Lens a b -> Lens a c -> Lens a ( b, c )

Tuple Lens a b with Lens a c and returns Lens a (b,c)

tuple3 : Lens a b -> Lens a c -> Lens a d -> Lens a ( b, c, d )

Tuple Lens a b with Lens a c with Lens a d and returns Lens a (b,c,d)

Conversion

fromIso : Monocle.Iso.Iso a b -> Lens a b

Casts Iso a b to Lens a b