Created
February 5, 2018 23:14
-
-
Save marick/43c5ba5e388ec08504d9897c88661c9a to your computer and use it in GitHub Desktop.
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
> To show the use of `map` and `andThen`, let me define a function | |
> `headButLast` that takes the `head` of a `List String` and removes its last | |
> character: | |
> | |
> {lang=elm} | |
> ~~~~~~~~~~~~~~ | |
> > headButLast ["Dawn"] | |
> Just "Daw" : Maybe.Maybe String | |
> ~~~~~~~~~~~~~~ | |
> | |
> Such a function must handle two | |
> unhappy cases: | |
> | |
> 1. The list is empty: | |
> | |
> {lang=elm} | |
> ~~~~~~~~~~~~~~ | |
> > headButLast [] | |
> Nothing : Maybe.Maybe String | |
> ~~~~~~~~~~~~~~ | |
> | |
> 2. The list has a `head` but it's the empty string (and the empty | |
> string doesn't have a last character): | |
> | |
> {lang=elm} | |
> ~~~~~~~~~~~~~~ | |
> > headButLast [""] | |
> Nothing : Maybe.Maybe String | |
> ~~~~~~~~~~~~~~ | |
> | |
> Here's the implementation: | |
> | |
> {lang=elm} | |
> ~~~~~~~~~~~~~~~~~~ | |
> headButLast : List String -> Maybe String | |
> headButLast list = | |
> list -- ["Dawn"] | |
> |> List.head -- Just "Dawn" | |
> |> Maybe.map String.reverse -- Just "nwaD" | |
> |> Maybe.andThen String.uncons -- Just (n, "waD") | |
> |> Maybe.map Tuple.second -- Just "waD" | |
> |> Maybe.map String.reverse -- Just "Daw" | |
> ~~~~~~~~~~~~~~~~~~ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What would be idiomatic PureScript?
Something else?