How can different types share data?
Question
Solution
Alternative Solution
1
type Animal
2
= Dog DogData
3
| Bird BirdData
4
5
type alias DogData =
6
{ name : String
7
, runningSpeed : Float
8
}
9
10
type alias BirdData =
11
{ name : String
12
, wingSpan : Float
13
}
14
​
15
{-| This function should work for all Animals
16
-}
17
getName {name} =
18
name
Copied!
1
type alias Animal =
2
{ name : String, data : AnimalData}
3
​
4
type AnimalData
5
= Dog DogData
6
| Bird BirdData
7
8
type alias DogData =
9
{ runningSpeed : Float
10
}
11
12
type alias BirdData =
13
{ wingSpan : Float
14
}
15
​
16
getName : Animal -> String
17
getName {name} =
18
name
Copied!
1
type Animal =
2
Dog DogData
3
| Bird BirdData
4
​
5
type alias AnimalData species =
6
{species| name : String}
7
8
type alias DogData =
9
AnimalData {runningSpeed:Float}
10
​
11
type alias BirdData =
12
AnimalData {wingSpan:Float}
13
​
14
getName : AnimalData species -> String
15
getName {name} =
16
name
Copied!

Question

How can I write one function for all animals, that returns just the name.

Answer

Put the common data, in our case the name, all in one case and separate it from the differing data.

Further Reading

​