sandboxj
sandboxj

Reputation: 1254

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?

E.g. if the argument of the function is a tuple, add them, if it is just an int, use 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.

Upvotes: 0

Views: 85

Answers (3)

Dusterbraut
Dusterbraut

Reputation: 54

In Miranda, function must be of given type. For example:

Your first line:

form (x, y) = x + y

has type:

form :: (num,num) -> num

There are two solutions:

  1. Use abstract type with alternative cases
  2. Use dynamic FP language (I like Erlang).

Upvotes: 0

Cirdec
Cirdec

Reputation: 24156

You can do this with a type class. We can define the class of Formable types that have a form function:

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

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. 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

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

Upvotes: 4

Redu
Redu

Reputation: 26161

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 

Upvotes: 1

Related Questions