Search code examples
genericstypesannotationsrecordelm

How do I specify generic type anotations in Elm?


Does elm have a "generics" system? For example I have a function say setTime that takes a record and changes the .date to the current time. Now, if I have multiple records with a .date how can I use the same function on multiple different records? I tried setting the signature to a -> a but then I get the error

Your type annotation uses type variable `a` which means ANY type of value
can flow through, but your code is saying it specifically wants a record. Maybe
change your type annotation to be more specific?

Can I just make the type annotation require a record with a .date , if so how?


Solution

  • you can write:

    setTime : Date -> { a | date : Date } -> { a | date : Date }
    

    Where { a | data : Date } is saying any value that is a record with a field named date whose type is Date.


    If you use it a lot and want to avoid some tedium, you could also wrap that partial record in a type alias

    type alias Dated a = { a | date : Date }
    setTime : Date -> Dated a -> Dated a
    

    And also, you could chain those

    type alias Dated a = { a | date : Date }
    type alias Checked a { a | check : Bool }
    checkAtTime : Date -> Dated (Checked a) -> Dated (Checked a)