LLM docs

Result

Result ok err : [ Ok ok, Err err ]

The result of an operation that could fail: either the operation went okay, or else there was an error of some sort.

isOk : Result ok err -> Bool

Returns Bool.true if the result indicates a success, else returns Bool.false

Result.isOk (Ok 5)

isErr : Result ok err -> Bool

Returns Bool.true if the result indicates a failure, else returns Bool.false

Result.isErr (Err "uh oh")

withDefault : Result ok err, ok -> ok

If the result is Ok, returns the value it holds. Otherwise, returns the given default value.

Result.withDefault (Ok 7) 42
Result.withDefault (Err "uh oh") 42

map : Result a err, (a -> b) -> Result b err

If the result is Ok, transforms the value it holds by running a conversion function on it. Then returns a new Ok holding the transformed value. If the result is Err, this has no effect. Use mapErr to transform an Err.

Result.map (Ok 12) Num.neg
Result.map (Err "yipes!") Num.neg

Functions like map are common in Roc; see for example List.map, Set.map, and Dict.map.

mapErr : Result ok a, (a -> b) -> Result ok b

If the result is Err, transforms the value it holds by running a conversion function on it. Then returns a new Err holding the transformed value. If the result is Ok, this has no effect. Use map to transform an Ok.

Result.mapErr (Err "yipes!") Str.isEmpty
Result.mapErr (Ok 12) Str.isEmpty

mapBoth : Result ok1 err1, (ok1 -> ok2), (err1 -> err2) -> Result ok2 err2

Maps both the Ok and Err values of a Result to new values.

map2 : Result a err, Result b err, (a, b -> c) -> Result c err

Maps the Ok values of two Results to a new value using a given transformation, or returns the first Err value encountered.

try : Result a err, (a -> Result b err) -> Result b err

If the result is Ok, transforms the entire result by running a conversion function on the value the Ok holds. Then returns that new result. If the result is Err, this has no effect. Use onErr to transform an Err.

Result.try (Ok -1) \num -> if num < 0 then Err "negative!" else Ok -num
Result.try (Err "yipes!") \num -> if num < 0 then Err "negative!" else Ok -num

onErr : Result a err, (err -> Result a otherErr) -> Result a otherErr

If the result is Err, transforms the entire result by running a conversion function on the value the Err holds. Then returns that new result. If the result is Ok, this has no effect. Use try to transform an Ok.

Result.onErr (Ok 10) \errorNum -> Str.toU64 errorNum
Result.onErr (Err "42") \errorNum -> Str.toU64 errorNum

onErr! : Result a err, (err => Result a otherErr) => Result a otherErr

Like onErr, but it allows the transformation function to produce effects.

Result.onErr (Err "missing user") \msg ->
    try Stdout.line! "ERROR: $(msg)"
    Err msg