user2167582
user2167582

Reputation: 6368

how to list out a certain type definition in elm

type alias Employee =
    { role : Role, name : String }


type Role
    = Engineer
    | Manager
    | Sales
    | Accounting
    | Hr


generateSample =
    Role.all |> List.map createModelWithType

I need to accomplish Role.all, which even Role in this case is inaccessible. What's the best way to accomplish / alternative way to express this.

Upvotes: 2

Views: 389

Answers (2)

VGj.
VGj.

Reputation: 119

There are many considerations when choosing a type. It depends on what behavior will be used with the data. Maybe as you are learning you could simply choose a data type that works and seems simple enough to work with. With experience you will see the advantages of choosing a type over the other.

To get more inspired in the way of thinking in choosing type for different problems you might want to take a look at this presentation: https://www.youtube.com/watch?v=XpDsk374LDE There are two topics mixed in the presentation and one of them is how choosing type for different behaviors.

Here is one way to do it:

type Alias Role = 
     { Engineer : Bool
     , Manager : Bool
     , Sales : Bool
     , Accounting : Bool
     , Hr : Bool
     }

Upvotes: 2

Chad Gilbert
Chad Gilbert

Reputation: 36375

There is no automatic way to list all constructors of a type. You could build a list like this:

allRoles : List Role
allRoles =
    [ Engineer
    , Manager
    , Sales
    , Accounting
    , Hr
    ]

In Elm, there is no concept of a simple enumeration similar to other languages. Type constructors could also have arguments, which may help in understanding why there is no built-in way to enumerate a list of constructors.

Upvotes: 7

Related Questions