Search code examples
elm

How to view custom type in elm?


here is data model , the goal is easy, just to view the type Gift in the HTML and user can use a dropdown list to update field type_ of Gift. But the question is how to build dropdown list from a custom type ?

type Fruit
    = Apple
    | Banana
    | Orange

type alias Gift = 
{ quantity : int
  type_ : Fruit
}

I tried to add a update/view operation on view

how to convert the type Fruit to String ? There are two possible workarounds:

  1. Building a dict, which mays Fruit to String

     {Apple:"Apple",Banana,"Banana"}
    

    I don't think this will work since key in Dict needs to be Comparable,but how to implement ordering in custom type ? there was an issue but there seems no solution yet (https://github.com/elm/compiler/issues/774)

  2. Using Enum/makeEnum module this will bring more code and easily can break.

     fruitTypeEnum = Enum.makeEnum [Apple, Banana, Orange ]
    
     -- in view
     (List.map (\x -> Enum.toString fruitTypeEnum x) [Apple,Banana,Orange])
    

    this has to maintain apple,banana,orange list in three places ( including the declaration )

Thank you for your time reading this .Appreciate any help:)


Solution

  • I'll only answer the first question here (see my comment). No Dict needed, it's a simple function:

    fruitToString : Fruit -> String
    fruitToString fruit =
      case fruit of
        Apple -> "Apple"
        Banana -> "Banana"
        Orange -> "Orange"