繁体   English   中英

模式匹配简单类型

[英]Pattern matching simple types

我是一个初学者,尝试学习函数式编程。

是否有一种模式可以匹配不同的标准(非用户定义)类型?

例如,如果函数的参数是一个元组,则添加它们;如果它只是一个int,则使用int:

form (x, y) = x + y
form any_num = any_num

这显然是行不通的,因为程序认为any_num只是任何元组,因此无法访问。

您可以使用类型类来执行此操作。 我们可以定义具有form功能的Formable类型的类:

class Formable a where
    form :: a -> Int

对于整数,只需使用整数

instance Formable Int where
    form x = x

如果参数是元组,则将其参数加在一起。 我打算走一步,而是只对元组的工作(Int, Int)其成型的实例可以在任何工作的元组(a, b)只要双方abFormable

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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM