模式匹配简单类型
Pattern matching simple types
我是一个尝试学习函数式编程的初学者。
有没有办法对不同的标准(非用户定义)类型进行模式匹配?
例如如果函数的参数是一个元组,添加它们,如果它只是一个 int,使用 int:
form (x, y) = x + y
form any_num = any_num
这显然行不通,因为程序认为 any_num 只是任何元组,因此无法访问。
我想你可能会这样做;
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
您可以使用 type class 来做到这一点。我们可以定义具有 form
函数的 Formable
类型的 class:
class Formable a where
form :: a -> 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
在 Miranda 中,函数必须是给定的类型。例如:
你的第一行:
form (x, y) = x + y
有类型:
form :: (num,num) -> num
有两种解决方案:
- 在替代案例中使用抽象类型
- 使用动态 FP 语言(我喜欢 Erlang)。
我是一个尝试学习函数式编程的初学者。
有没有办法对不同的标准(非用户定义)类型进行模式匹配?
例如如果函数的参数是一个元组,添加它们,如果它只是一个 int,使用 int:
form (x, y) = x + y
form any_num = any_num
这显然行不通,因为程序认为 any_num 只是任何元组,因此无法访问。
我想你可能会这样做;
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
您可以使用 type class 来做到这一点。我们可以定义具有 form
函数的 Formable
类型的 class:
class Formable a where
form :: a -> 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
在 Miranda 中,函数必须是给定的类型。例如:
你的第一行:
form (x, y) = x + y
有类型:
form :: (num,num) -> num
有两种解决方案:
- 在替代案例中使用抽象类型
- 使用动态 FP 语言(我喜欢 Erlang)。