我们可以使用类型同义词来定义函数,例如
type FuncDef = Int -> Int -> Int
这避免了我们每次都编写很长的函数定义。
用途:
someFunc :: FuncDef -> Int
而不是
someFunc :: (Int -> Int -> Int) -> Int
可读性更强,代码也更少。
简单的代数数据类型很简单并且易于进行模式匹配等,例如
data AType = X | Y | Z Int
matchType :: AType -> Bool
matchType X = ..
matchType Y = ..
matchType (Z _) = ..
当我更多地研究 Haskell 数据类型时,我发现在定义新类型时我们可以在数据构造函数中定义函数。
data MyType a b = X | Y (a -> b)
这让我有点困惑,而且还没有看到很多这样的例子。在某种程度上,高阶函数的想法(一个函数可以将另一个函数作为参数)与这种情况类似,只不过这里它适用于数据类型。 Haskell wiki 并没有过多提及“高阶数据类型定义”。我意识到我可能把所有这些术语都弄错了,所以请纠正我,并指出我要阅读更多内容。我真的很想看看它的具体用法。谢谢!
matchMyType :: (MyType a b) -> Bool
matchMyType X = ..
matchMyType Y ?? = ..
最佳答案
您可能会在很多情况下使用这种模式。例如,如果您想要一个以各种方式转换字符串的函数,您可能有这样的数据类型(这只是一个演示原理的示例 - 不要编写这样的代码!):
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)
然后,使用它的程序可能如下所示:
-- | 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
关于haskell - 新类型的数据构造函数中的函数定义示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8507724/