Skip to content

Instantly share code, notes, and snippets.

@marick
Created February 5, 2018 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marick/43c5ba5e388ec08504d9897c88661c9a to your computer and use it in GitHub Desktop.
Save marick/43c5ba5e388ec08504d9897c88661c9a to your computer and use it in GitHub Desktop.
> 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"
> ~~~~~~~~~~~~~~~~~~
@marick
Copy link
Author

marick commented Feb 6, 2018

What would be idiomatic PureScript?

headButLast1 list =
  String.reverse <$> _.tail <$> (String.uncons =<< String.reverse <$> head list)

headButLast2 list =
  head list <#> String.reverse >>= String.uncons <#> _.tail <#> String.reverse

headButLast3 list =
  head list
    <#> String.reverse
    >>= String.uncons
    <#> _.tail
    <#> String.reverse

Something else?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment