Search code examples
elm

Elm : How to make use of value with (Result String Value)


For example

fromIsoString : String -> Result String Date

fromIsoString will produce Ok (Value) ... Any methods that i can use to do something with the Value

As what i tested it is working with

text ( `Value` |> Date.add Days -1|> Date.toIsoString)

Method tried : Date.fromIsoString "2018-09-26" |> Result.withDefault 0 gives error -> expects:

Result String #Date#

Ideally i want to transform ISO date (2020-05-10) into Date format and do something with the date like -1 day.

Reference : https://github.com/justinmimbs/date/blob/3.2.0/src/Date.elm


Solution

  • You’re seeing this Result String #Date# error because you’ve passed Result.withDefault a number where it expects a Date. If we look at the withDefault type annotation:

    > Result.withDefault
    <function> : a -> Result x a -> a
    

    withDefault expects a default of the same type a as the successful result. Because you’ve specified 0 : number as the default, its type becomes:

    > \result -> Result.withDefault 0 result
    <function> : Result x number -> number
    

    Note that result's type is Result x number, which doesn't line up with fromIsoString's Result String Date output type.

    TLDR: Pass a Date as the default argument, e.g.:

    > defaultDate = Date.fromCalendarDate 2020 Jan 1
    RD 737425 : Date
    > Date.fromIsoString "2018-09-26" |> Result.withDefault defaultDate
    RD 736963 : Date
    

    Take a look at the Elm Result documentation for other functions you can call on values of type Result String Date