我是一个初学者,试图学习函数式编程。
有没有办法模式匹配不同的标准(不是用户定义的)类型?
例如,如果函数的参数是元组,则添加它们,如果它只是一个 int,则使用 int:
form (x, y) = x + y
form any_num = any_num
这显然是行不通的,因为程序认为any_num只是任何元组,因此无法访问。
您可以使用类型类执行此操作。我们可以定义具有form
函数的Formable
类型的类:
class Formable a where
form :: a -> Int
对于 int,只需使用 int
instance Formable Int where
form x = x
如果参数是元组,则将其参数相加。我将更进一步,不仅处理元组(Int, Int)
它的可形成实例就可以处理任何元组(a, b)
,只要a
和b
都Formable
instance (Formable a, Formable b) => Formable (a, b) where
form (a, b) = form a + form b
我们可以以类似的方式为其他类型的Formable
实例。就像对列表的元素求和一样
instance (Formable a) => Formable [a] where
form = sum . map form
或总和的替代方案
instance (Formable a, Formable b) => Formable (Either a b) where
form (Left a) = form a
form (Right b) = form b
甚至Maybe
,如果我们知道如何处理Nothing
instance (Formable a) => Formable (Maybe a) where
form Nothing = 0
form (Just a) = form a
我想你可以这样做;
form :: Either (Int,Int) Int -> Int
form (Left (n,m)) = n + m
form (Right n) = n
>> form (Left (2,3))
>> 5
>> form (Right 7)
>> 7
在米兰达中,函数必须是给定类型。例如:
您的第一行:
form (x, y) = x + y
具有类型:
form :: (num,num) -> num
有两种解决方案:
- 将抽象类型与替代情况一起使用
- 使用动态 FP 语言(我喜欢 Erlang)。