Skip to content

Instantly share code, notes, and snippets.

@jbrains
Last active July 2, 2017 02:00
Show Gist options
  • Save jbrains/a913064a932c7cc6c3a5424957f7c409 to your computer and use it in GitHub Desktop.
Save jbrains/a913064a932c7cc6c3a5424957f7c409 to your computer and use it in GitHub Desktop.
REVIEW: creating optional HTML from a Result in Elm
-- This becomes the typical pop-up error message at the top of an HTML page
failureView : Result String Int -> List (Html Update)
failureView possibleNumericInput =
case possibleNumericInput of
Err message ->
[ text message ]
Ok _ ->
[]
-- I like this version, but wonder if there's a more direct way.
-- I need the exact opposite of Result.withDefault that provides a default value for Ok instead of Err.
failureView : Result String Int -> List (Html Update)
failureView possibleNumericInput =
either
(text >> List.singleton)
(\_ -> [])
possibleNumericInput
-- This is pretty close to what I thought I wanted.
failureView : Result String Int -> List (Html Update)
failureView =
Exts.Result.fromErr >> Exts.List.maybeSingleton >> List.map Html.text
@jbrains
Copy link
Author

jbrains commented Jul 2, 2017

I would prefer a more direct route: something that just turns Result String Int into Maybe String (not the more usual Maybe Int) or that lets me map a function over the Errs and not the Oks. Haskell has Either.lefts, which would give me a path:

failureView = List.singleton >> Result.lefts >> (map Html.text)

(I think that's right. I'm still a beginner here.)

Suggestions?!

@jbrains
Copy link
Author

jbrains commented Jul 2, 2017

Of course! Now I see Result.fromErr. Can I do better?

Now that I've refactored a little, it's pretty good. :)

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