I was doing this type of thing in my code:
data MyType = Cons1 a b
data OtherType = OtherType
{ val1 :: Int
, val2 :: String
, val3 :: Maybe MyType
}
and I was wondering if changing the code to this would be neater/simpler and what the pros/cons are:
data MyType = Cons1 a b | Missing
data OtherType = OtherType
{ val1 :: Int
, val2 :: String
, val3 :: MyType
}
What I am doing is reading lines from a file into [OtherType], each line has 4 columns say with columns 3 and 4 being used to create val3 :: MyType. Currently I am using readMaybe to read a and b and then passing them to a function that returns Nothing if either of them are Nothing or Just MyType if they are Just a and Just b. I was thinking I could change this to return Missing instead thereby removing one layer of wrapping.
Wikipedia's list of programming languages with algebraic data types (ADTs) suggests that Rust indeed has ADTs, but I am not sure if my interpretation for why this is true for Rust is correct. As I understand it, to say that one has ADTs one needs to have: Values: Zero (or Void) - ! in Rust) - a type that gets no value.
This is a type where we specify the shape of each of the elements. Wikipedia has a thorough discussion. "Algebraic" refers to the property that an Algebraic Data Type is created by "algebraic" operations. The "algebra" here is "sums" and "products": "sum" is alternation ( A | B , meaning A or B but not both)
What Are Algebraic Data Types? ADTs are commonly used in Scala. Simply put, an algebraic data type is any data that uses the Product or Sum pattern.
Type constructor The data type is polymorphic (and a is a type variable that is to be substituted by a specific type). So when used, the values will have types like Tree Int or Tree (Tree Boolean) .
You should only add the Missing
constructor to MyType
if it makes sense for all MyType
values to have the possibility of Missing
. You will have to handle Missing
in all functions dealing with MyType
values. If the majority of these would be non-total—throw an error or otherwise fail—then clearly Missing
does not belong in MyType
and you should just use Maybe MyType
instead.
Simply put: if optionality is inherent in the type, encode it in the type. Otherwise, keep it separate.
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