简体   繁体   English

模式匹配简单类型

[英]Pattern matching simple types

I am a beginner trying to learn functional programming. 我是一个初学者,尝试学习函数式编程。

Is there a way to pattern match different standard (not user defined) types? 是否有一种模式可以匹配不同的标准(非用户定义)类型?

Eg if the argument of the function is a tuple, add them, if it is just an int, use int: 例如,如果函数的参数是一个元组,则添加它们;如果它只是一个int,则使用int:

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

This obviously won't work, because the program thinks any_num is just any tuple and is therefore unreachable. 这显然是行不通的,因为程序认为any_num只是任何元组,因此无法访问。

You can do this with a type class . 您可以使用类型类来执行此操作。 We can define the class of Formable types that have a form function: 我们可以定义具有form功能的Formable类型的类:

class Formable a where
    form :: a -> Int

For ints, just use the int 对于整数,只需使用整数

instance Formable Int where
    form x = x

If the argument is a tuple, add its arguments together. 如果参数是元组,则将其参数加在一起。 I'm going to go one step further, and instead of only working on tuples (Int, Int) its formable instance will work on any tuple (a, b) as long as both a and b are Formable 我打算走一步,而是只对元组的工作(Int, Int)其成型的实例可以在任何工作的元组(a, b)只要双方abFormable

instance (Formable a, Formable b) => Formable (a, b) where
    form (a, b) = form a + form b

We can write Formable instances for other types in a similar vein. 我们可以类似的方式为其他类型编写Formable实例。 Like totaling the elements of a list 就像汇总列表中的元素

instance (Formable a) => Formable [a] where
    form = sum . map form

or the alternatives of a sum 或总和的替代

instance (Formable a, Formable b) => Formable (Either a b) where
    form (Left a) = form a
    form (Right b) = form b

or even Maybe , if we know what to do with Nothing 甚至Maybe ,如果我们知道怎么做Nothing

instance (Formable a) => Formable (Maybe a) where
    form Nothing = 0
    form (Just a) = form a

I guess you may do as follows; 我想您可以按照以下步骤进行:

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