khaled alomar
khaled alomar

Reputation: 683

transform a list of string to list of tuples using foldl function

I have the below function :

fn :: [String] -> [(a,b,c)]
fn lst = case lst of
  [] -> []
  (a:b:c:xs) -> (a,b,c) : fn xs

I want to write this function using foldl or foldr

Upvotes: 1

Views: 360

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76297

I want to write this function using foldl or foldr

This is somewhat ugly, but it technically solves it with foldr (it would be easy to adapt it to foldl):

fn :: String -> [(Char, Char, Char)]                                                                                                                                                                    
fn s = snd $ foldr toTriples ([], []) s where
    toTriples :: Char -> (String, [(Char, Char, Char)]) -> (String, [(Char, Char, Char)])
    toTriples c (cur, tups) | length cur < 2 = (c:cur, tups)
    toTriples c (cur, tups) = ([], (c, cur!!0, cur!!1):tups)

As the accumulator, it uses a pair of cur, the current part of the tuple being scanned, and tups, a list of tuples.

  • If the length of cur is less than 2, it prepends the current character to it.

  • If the length of cur is 2, it creates a tuple and prepends it to the list of tuples.

Upvotes: 1

Related Questions