Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write the function 'pairs' in Haskell?

Tags:

The pairs function needs to do something like this:

pairs [1, 2, 3, 4] -> [(1, 2), (2, 3), (3, 4)]
like image 668
unj2 Avatar asked Mar 30 '10 15:03

unj2


People also ask

How do I make a pair in Haskell?

Use parentheses and commas to create tuples. Use one comma to create a pair. Use more commas to create tuples with more components. Note that it is also possible to declare tuples using in their unsugared form.

How are functions defined in Haskell?

The most basic way of defining a function in Haskell is to ``declare'' what it does. For example, we can write: double :: Int -> Int double n = 2*n. Here, the first line specifies the type of the function and the second line tells us how the output of double depends on its input.

What does == mean in Haskell?

The == is an operator for comparing if two things are equal. It is quite normal haskell function with type "Eq a => a -> a -> Bool". The type tells that it works on every type of a value that implements Eq typeclass, so it is kind of overloaded.

How do you extract values from tuple in Haskell?

Use the fst and snd functions (from Prelude or Data. Tuple ) to extract the first and second component of pairs. Or use pattern matching. Pattern matching also works for tuples with more than two components.


1 Answers

pairs [] = []
pairs xs = zip xs (tail xs)
like image 103
Dietrich Epp Avatar answered Sep 30 '22 06:09

Dietrich Epp