模式匹配简单类型

时间:2017-04-29 18:31:29

标签: haskell pattern-matching miranda

我是初学者,正在尝试学习函数式编程。

有没有办法模式匹配不同的标准(非用户定义)类型?

E.g。如果函数的参数是一个元组,添加它们,如果它只是一个int,则使用int:

Ctrl+C

这显然不会起作用,因为该程序认为any_num只是任何元组,因此无法访问。

2 个答案:

答案 0 :(得分:3)

您可以使用type class执行此操作。我们可以定义具有Formable函数的form类型的类:

class Formable a where
    form :: a -> Int

对于int,只需使用int

instance Formable Int where
    form x = x

如果参数是元组,请将其参数添加到一起。我将更进一步,而不是只处理元组(Int, Int),只要(a, b)和{{1},它的可形成实例将适用于任何元组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

答案 1 :(得分:1)

我猜你可以这样做;

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 
相关问题