Restrict records using Opaque Types
type alias Movie =
{ title : String
, rating : Int
}
{-| adds a Rating to a Movie,
Only allows ratings between 1 and 5.
-}
addRating : Int -> Movie -> Movie
addRating rating movie =
{ movie | rating = rating}
Question
How can I only allow specific states for my type?
Answer
Place the type into a new File and don't expose the constructor: exposing (Movie)
instead of exposing(Movie(..))
.
Then write your own constructors.
Further reading
📖Book: Beginning Elm by Pawan Poudel
📄Article: Advanced Types in Elm - Opaque Types by Charlie Koster
👥Thread: Post-update invariant repair: good idea or bad?
Last updated
Was this helpful?