🌳
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

How can different types share data?

type Animal
    = Dog DogData
    | Bird BirdData
    
type alias DogData =
    { name : String
    , runningSpeed : Float
    }
    
type alias BirdData =
    { name : String
    , wingSpan : Float
    }

{-| This function should work for all Animals
-}
getName {name} =
    name
type alias Animal =
    { name : String, data : AnimalData}

type AnimalData
    = Dog DogData
    | Bird BirdData
    
type alias DogData =
    { runningSpeed : Float
    }
    
type alias BirdData =
    { wingSpan : Float
    }

getName : Animal -> String
getName {name} =
    name
type Animal =
    Dog DogData
    | Bird BirdData

type alias AnimalData species =
    {species| name : String}
    
type alias DogData =
    AnimalData {runningSpeed:Float}

type alias BirdData =
    AnimalData {wingSpan:Float}

getName : AnimalData species -> String
getName {name} =
    name

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

PreviousStructure of the bookNextHow to break Dependency Cycles?

Last updated 5 years ago

Was this helpful?

👥Thread:

Passing accessors to functions