What are comparable types?
Problem
Solution
1
type FruitSort =
2
Apple
3
| Orange
4
| Banana
5
​
6
type alias Fruit =
7
{ sort: FruitSort
8
, name: String
9
}
10
​
11
{-| Fruit needs to be "comparable". What do i need to do?
12
-}
13
type Basket =
14
Dict Fruit Int
Copied!
1
type FruitSort =
2
Apple
3
| Orange
4
| Banana
5
​
6
fruitSortToInt : FruitSort -> Int
7
fruitSortToInt fruit =
8
case fruit of
9
Apple -> 1
10
Orange -> 2
11
Banana -> 3
12
​
13
fruitSortFromInt : Int -> FruitSort
14
fruitSortFromInt int =
15
case int of
16
1 -> Apple
17
2 -> Orange
18
3 -> Banana
19
_ -> Apple --be careful, the compiler won't help you there.
20
​
21
type alias Fruit =
22
{ sort: FruitSort
23
, name: String
24
}
25
​
26
type alias Item =
27
(Int,String)
28
​
29
itemFromFruit : Fruit -> Item
30
itemFromFruit {sort,name} =
31
(sort |> fruitSortToInt,name)
32
​
33
itemToFruit : Item -> Fruit
34
itemToFruit (int,name) =
35
{ sort = int |> fruitSortFromInt
36
, name = name
37
}
38
​
39
type Basket =
40
Dict Item Int
Copied!

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