🌳
Walking though the Elm woods
  • Introduction
  • Structure of the book
  • Frequently asked questions
    • How can different types share data?
    • How to break Dependency Cycles?
    • How to structure an Elm project?
    • How to turn a Msg into a Cmd Msg?
    • How to update nested Records?
    • What are comparable types?
    • Why are Booleans bad?
    • 🔜Future topics
  • Recipes
    • Writing a Single Page Application
      • Share state across pages
      • Debounced Validation
      • Reusable views
    • Making impossible states Impossible
      • Non empty lists using Zippers
      • Restrict records using Opaque Types
      • Write safer functions using Phantom Types
    • Designing Elm package APIs
      • Create upwards compatible APIs
    • 🔜Future topics
  • Frameworks and packages
    • elm/parser
    • mdgriffith/elm-ui
    • 🔜Future topics
Powered by GitBook
On this page
  • Question
  • Answer
  • Further reading

Was this helpful?

  1. Frequently asked questions

What are comparable types?

type FruitSort =
    Apple
    | Orange
    | Banana

type alias Fruit =
    { sort: FruitSort
    , name: String
    }

{-| Fruit needs to be "comparable". What do i need to do?
-}
type Basket =
    Dict Fruit Int
type FruitSort =
    Apple
    | Orange
    | Banana

fruitSortToInt : FruitSort -> Int
fruitSortToInt fruit =
    case fruit of
        Apple -> 1
        Orange -> 2
        Banana -> 3

fruitSortFromInt : Int -> FruitSort
fruitSortFromInt int =
   case int of
       1 -> Apple
       2 -> Orange
       3 -> Banana
       _ -> Apple --be careful, the compiler won't help you there.

type alias Fruit =
    { sort: FruitSort
    , name: String
    }

type alias Item =
    (Int,String)

itemFromFruit : Fruit -> Item
itemFromFruit {sort,name} =
    (sort |> fruitSortToInt,name)

itemToFruit : Item -> Fruit
itemToFruit (int,name) =
    { sort = int |> fruitSortFromInt
    , name = name
    }

type Basket =
    Dict Item Int

Question

Dict needs the first type to be comparable. What does that mean?

Answer

Int, Float, Char, String, Tuple comparable comparable and List comparable are comparable types. So you need to convert Fruit into a comparable type like Tuple Int String.

Further reading

PreviousHow to update nested Records?NextWhy are Booleans bad?

Last updated 5 years ago

Was this helpful?

📦Package: Use any type with .

📦Package: use any type with .

turboMaCk/any-dict
turboMaCk/any-set