Home > other >  Defining the function pairs with Relude/as safe function
Defining the function pairs with Relude/as safe function

Time:10-19

Hello so I'm trying to define the function pairs:

pairs :: [a] -> [(a, a)]
pairs x = zip x (tail x)

However I'm using Relude as opposed to the normal Prelude. Which makes tail work with Non-Empty a rather then [a]. This has lead to some really confusing stuff when I try to fix it. As switching the [a] to [nonEmpty a] etc. Leads to the problem moving around.

Any ideas on how to alter the function so it works with relude?.

It also has it seems a way of doing things with the viaNonEmpty function however using this also has problems.

Ultimately all I want to do is just be able to take [a] and create [(a, a)], and the zip xs (tail xs) method seemed from looking around to be the idiomatic way of doing this. But if this way is not doable using relude alright then.

Any help is most appreciated. Thanks.

CodePudding user response:

You can use drop 1 instead of tail. The reason why that is safer is because drop 1 [] = [], while tail [] throws an exception.

Alternatively, you can use pattern matching directly:

pairs [] = []
pairs xs@(_:xs') = zip xs xs'

CodePudding user response:

You can avoid tail if you handle the empty list case first:

pairs :: [a] -> [(a, a)]
pairs []     = ...
pairs (x:xs) = zip ... ...
  • Related