How to display OK results

I play with Elm examples, and I noticed that field gives types Result. After getting stuck, I came up with this simplified case:

import Html exposing (text)
import String

f: Int -> Int
f x = x + 1

g: Result String Int -> Result String Int
g x = (Result.map f) x

main =
  text (  toString ( g  (String.toInt 5 ) ))

The result displays , and I would prefer it to display only . I know that it accepts any type and returns a string representation of This. So maybe I can change OK 6 6toStringtoString

  • if the result OK, then I can print the numerical result
  • if the result Err, then I would like to make some kind of custom error message

Perhaps this is the reason andThen, as the operation + 1may fail.

andThen : Result e a -> (a -> Result e b) -> Result e b
andThen result callback =
    case result of
      Ok value -> callback value
      Err msg -> Err msg

A definition is exactly what it does ... and is an instance . andThencase

andThen, case ? , . .

+4
1

, - , Err (-) Ok (-). , , . - , , String Html. , HTML.

, , . , , Err.

foo: Result String Err -> String
foo myres = 
  case myres of 
    Ok(str) -> str
    Err(e) -> "there was an error! uh oh"

, . , ? , :

View: Model -> Html
View model = 
  case makeMyHtml(model) of 
    Ok(htm) -> htm
    Err(e) -> renderSpecialErrorHtmlPage(e)

, "", :

main =
  let res = g  (String.toInt 5 ) 
  text (  toString ( Result.withDefault "g returned an error!" res)) 

g Ok (6), "6", , "g !".

+4

Source: https://habr.com/ru/post/1625680/


All Articles