π³
π³
π³
π³
Walking though the Elm woods
Searchβ¦
π³
π³
π³
π³
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
Making impossible states Impossible
Non empty lists using Zippers
Restrict records using Opaque Types
Write safer functions using Phantom Types
Designing Elm package APIs
π
Future topics
Frameworks and packages
elm/parser
mdgriffith/elm-ui
π
Future topics
Powered By
GitBook
Write safer functions using Phantom Types
Problem
Solution
1
type alias LoginForm =
2
{ username : String
3
, password : String
4
, isValid : Bool
5
}
6
β
7
{-| Creates a User
8
β
9
Only use this function if the LoginForm was validated.
10
-}
11
createUser : LoginForm -> User
12
createUser loginForm =
13
if loginForm.isValid then
14
User.create loginForm.username
15
else
16
Debug.todo "This should not happen."
Copied!
1
type LoginForm valid =
2
LoginForm
3
{ username : String
4
, password : String
5
}
6
β
7
type Valid = Valid
8
β
9
{-| Creates a User
10
-}
11
createUser : LoginForm Valid -> User
12
createUser (LoginForm loginForm) =
13
User.create loginForm.username
14
15
validate : LoginForm () -> LoginForm Valid
16
validate =
17
...
Copied!
Question
How can I ensure that a user can only be created with a valid login form?
Answer
Use a so called Phantom Type:
1
type LoginForm valid = --valid is not used in the definition
2
LoginForm
3
{ username : String
4
, password : String
5
}
6
7
type Valid = Valid
Copied!
Use
LoginForm ()
for unvalidated forms and
LoginForm Valid
for validated ones.
Further reading
π
Article:
Advanced Types in Elm - Phantom Types
by Charlie Koster
Previous
Restrict records using Opaque Types
Next - Recipes
Designing Elm package APIs
Last modified
2yr ago
Copy link
Contents
Question
Answer
Further reading