khaled el omar
khaled el omar

Reputation: 149

Implement recursion using foldl in haskell

given the below code

pair :: [String] -> [(String,String)]
pair [] = []
pair (x:xs)= zip [x] xs ++ pair xs

how could I rewrite it using Fold to avoid repetition ?

Upvotes: 0

Views: 288

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

A fold is going to be a bit messy for this particular problem because your folding function depends upon the previously visited elements in the list, with a two-value list minimum. And since folding visits elements one at a time, you have to decide what to do when there's only one element in the list.

Here is an example that creates a dummy element for the singleton list case and discards it with init.

pair :: [String] -> [(String, String)]
pair = init . foldr f []
  where
    f x acc =
      case acc of
        [] -> [(x, "discarded")]
        z@(y:_) -> (x, fst y) : z

If you're tasked with learning about folds, take a minute to understand why we have to handle it in such an unsatisfactory way. Otherwise, if you're looking to do this in the least amount of code, see @DavideSpataro's answer above of zip xs (tail xs).

Upvotes: 1

Related Questions