We can use type synonym for function definitions, e.g.
type FuncDef = Int -> Int -> Int
This avoids us writing long function definition every time.
Use:
someFunc :: FuncDef -> Int
Instead of
someFunc :: (Int -> Int -> Int) -> Int
which is more readable and less code as well.
Simple algebraic data types are straight forward and easy to do pattern matching etc, e.g.
data AType = X | Y | Z Int
matchType :: AType -> Bool
matchType X = ..
matchType Y = ..
matchType (Z _) = ..
As I look more into Haskell data types, I found we can have function definition in data constructor when defining new type.
data MyType a b = X | Y (a -> b)
This puzzles me a bit and haven’t seen many examples of this around. In a way, the idea of high-order function where a function can take another function as argument is similar to this situation, except here it applies to data type. The Haskell wiki does not say much about “high-order data type definition”. I realise I may be getting all these terms wrong, so please correct me, and point me to more reading. I really want to see a concrete usage of this. Thanks!
matchMyType :: (MyType a b) -> Bool
matchMyType X = ..
matchMyType Y ?? = ..
You might use this kind of pattern in many situations. For example, if you want a function that transforms strings in various ways, you might have a data type like this (This is just an example that demonstrates the principle – don’t write code like this!):
Then, a program that uses this might look like: