When you define a class in a object-oriented language it usually sets the default values for the member variables. Is there any mechanism in Haskell to do the same thing in record types? And a follow up question: If we don't know from the very start all the values for a data constructor but we obtain them from IO interaction can we build the type using something like the builder pattern from OOP?
Thanks in advance
The Haskell standard data type Maybe is typically declared as: data Maybe a = Just a | Nothing. What this means is that the type Maybe has one type variable, represented by the a and two constructors Just and Nothing. (Note that Haskell requires type names and constructor names to begin with an uppercase letter).
In computer technology, a default (noun, pronounced dee-FAWLT ) is a predesigned value or setting that is used by a computer program when a value or setting is not specified by the program user.
Haskell has three basic ways to declare a new type: The data declaration, which defines new data types. The type declaration for type synonyms, that is, alternative names for existing types. The newtype declaration, which defines new data types equivalent to existing ones.
Everything in Haskell has a type, so the compiler can reason quite a lot about your program before compiling it. Unlike Java or Pascal, Haskell has type inference.
A common idiom is to define a default value.
data A = A { foo :: Int , bar :: String }
defaultA :: A
defaultA = A{foo = 0, bar = ""}
This can be then (purely) "updated" later on with real values.
doSomething :: Bool -> A
doSomething True = defaultA{foo = 32}
doSomething False = defaultA{bar = "hello!"}
Pseudocode example:
data Options = O{ textColor :: Bool, textSize :: Int, ... }
defaultOptions :: Options
defaultOptions = O{...}
doStuff :: Options -> IO ()
doStuff opt = ...
main :: IO ()
main = do
...
-- B&W, but use default text size
doStuff defaultOptions{ color = False }
If there are no sensible default values, you can wrap the field values in Maybe
.
If you feel adventurous, you can even use a more advanced approach to statically separate "intermediate" options values, which can lack a few fields, from "finalized" ones, which must have all the fields. (I'd not recommend this to Haskell beginners, though.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With