arturopala/elm-monocle/1.4.0

NOTE: this package is not compatible with Elm 0.19.1

Monocle.Prism

A Prism is a tool which optionally converts elements of type A into elements of type B and back.

Definition

type alias Prism a b =
{ getOption : a -> Maybe b
, reverseGet : b -> a
}

In order to create a Prism we need to supply two functions: getOption and reverseGet

Example

string2IntPrism : Prism String Int
string2IntPrism =
    Prism (String.toInt >> Result.toMaybe) toString


string2IntPrism.getOption "17896" == Just 17896
string2IntPrism.getOption "1a896" == Nothing
string2IntPrism.reverseGet 1626767 = "1626767"

Derived methods

isMatching : Prism a b -> a -> Bool

Checks if value of type A has matching element of type 'B'

    Monocle.Prism.isMatching string2IntPrism "abc" == False
    Monocle.Prism.isMatching string2IntPrism "123" == True
modify : Prism a b -> (b -> b) -> a -> a

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

    fx i = i * 2
    modified = Monocle.Prism.modify string2IntPrism fx
    modified "22" == "44"
    modified "abc" == "abc"
modifyOption : Prism a b -> (b -> b) -> a -> Maybe a

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

    fx i = i * 2
    modified = Monocle.Prism.modify string2IntPrism fx
    modified "22" == Just "44"
    modified "abc" == Nothing
compose : Prism a b -> Prism b c -> Prism a c

Composes Prism a b with Prism b c and returns Prism a c

    prism = Monocle.Prism.compose string2FloatPrism float2IntPrism
    prism.getOption "22" == Just 22
    prism.getOption "22.2" == Nothing
    prism.getOption "22a" == Nothing
    prism.getOption "abc" == Nothing
composeIso : Prism a b -> Iso b c -> Prism a c

Composes Prism a b with Iso b c and returns Prism a c

    iso = Iso ((*) 10) ((//) 10)
    prism = Monocle.Prism.composeIso string2IntPrism iso
    prism.getOption "22" == Just 220
    prism.getOption "22.2" == Nothing
    prism.getOption "22a" == Nothing
    prism.getOption "abc" == Nothing

Conversion

fromIso : Iso a b -> Prism a b

Casts Iso a b to Prism a b