Onni Pylvänen
Onni Pylvänen

Reputation: 19

Extract Integer from a datatype

I know i can do something like this to get an integer out of a datatype:

[x | (PhoneNo x) <- [PhoneNo 1234]]

where PhoneNo is defined as:

data PhoneNo = PhoneNo Integer deriving (Eq, Ord)

However this is better for lists. How can I extract the integer of a single PhoneNo instance?

Upvotes: 1

Views: 148

Answers (1)

justkris
justkris

Reputation: 810

Pattern matching is the canonical mechanism to deconstruct algebraic data types. You are already using it in your example: PhoneNo x is a pattern against which the value PhoneNo 1234 is matched, binding x to 1234 in the head of the list comprehension (here simply x).

Pattern matching happens a number of places in Haskell, most notably in function definitions:

extract :: PhoneNo -> Integer
extract (PhoneNo x) = x

Alternatively, you can match values against patterns in let, where and case expressions:

let (PhoneNo x) = PhoneNo 1234 in ... x ...

myFunction = ... x ...
   where
     (PhoneNo x) = PhoneNo 1234

case PhoneNo 1234 of
  PhoneNo x -> .... x ... 

Upvotes: 5

Related Questions