An example of a function definition in a data type constructor of a new type

We can use a type synonym for function definitions, for example.

type FuncDef = Int -> Int -> Int 

This allows us to write a long definition of a function each time.

Using:

 someFunc :: FuncDef -> Int 

Instead

 someFunc :: (Int -> Int -> Int) -> Int 

which is more readable and less code.

Simple types of algebraic data are straightforward and easily perform pattern matching, etc., for example.

 data AType = X | Y | Z Int matchType :: AType -> Bool matchType X = .. matchType Y = .. matchType (Z _) = .. 

Since I look more at Haskell data types, I found that when defining a new type, we can have a function definition in the data constructor.

 data MyType ab = X | Y (a -> b) 

This is a bit perplexing to me and have not seen many examples of this. In a sense, the idea of ​​a higher-order function, where a function can take another function as an argument, is similar to this situation, except that it applies to a data type. The Haskell wiki doesn't say much about "defining a high-order data type." I understand that I can be mistaken in all these terms, so please correct me and point me more. I really want to see the specific use of this. Thanks!

 matchMyType :: (MyType ab) -> Bool matchMyType X = .. matchMyType Y ?? = .. 
+8
types pattern-matching haskell
source share
2 answers

In many situations, you can use such a template. For example, if you need a function that converts strings differently, you may have this type of data (this is an example that demonstrates the principle - do not write such code!):

 data StringTransformation = -- | Doesn't transform the string at all NoTransformation | -- | Takes the string and generates a suffix that should be appended Append (String -> String) | -- | Takes the string and generates a prefix that should be prepended Prepend (String -> String) | -- | Takes the string and transforms it arbitrarily to a new string Map (String -> String) 

Then the program that uses this might look like this:

 -- | Returns 'True' if the name is male isMaleName :: String -> Bool isMaleName = ... -- | Adds a title to a name, for example "John Smith" -> "Mr. John Smith" addTitle :: StringTransformation addTitle = PrependTransformation $ \ name -> if isMaleName name then "Mr. " else "Mrs. " -- Applies a string transformation to a 'String'. transformString :: StringTransformation -> String -> String transformString NoTransformation str = str transformString (Append f) str = str ++ f str transformString (Prepend f) str = f str ++ str transformString (Map f) str = f str 
+11
source share
 data Thingy ab = A b | B (a -> b) really :: Thingy ab -> a -> b really (A x) _ = x -- x :: b really (B f) y = fy -- f :: a -> b, y :: a, fy :: b 

As CAMcCann says, there is nothing special about functions.

+4
source share

All Articles