-4

Need to implement a split with foldl or foldr.

For example: split [2, 4, 6, 8, 7] into ([2, 6, 7], [4, 8]).

Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • 2
    Voting as unclear what you're asking because it's unclear what you're asking. You should at minimum include a description of the problem you're having as well as what your attempts to solve it so far were. – Cubic May 01 '18 at 12:40
  • this question is a duplicate of https://stackoverflow.com/questions/3707753/haskell-split-even-and-odd-elements-into-tuple – Will Ness May 01 '18 at 23:40

2 Answers2

2

This is relatively straight-forward. We know the type of our "seed" for the fold, it must be a pair of lists. We alternate which list of the two lists we're appending to by simply swapping the two lists, and we append to list on the left (which will change between each iteration).

foldr (\x (ys,zs) -> (x:zs, ys)) ([],[]) [2,4,6,8,7]  -- ([2,6,7],[4,8])

If we were to use foldl the lists would come out backwards, so foldr seems like the logical choice.

Probie
  • 1,371
  • 7
  • 15
  • I guess we can generalise it to something like `insertAndSwap x (xss,[]) = insertAndSwap x ([],reverse xss)` `insertAndSwap x (yss,(zs:zss)) = ((x:zs):yss, zss)` `split n | n > 0 = (\(x,y) -> x ++ reverse y) . foldr swap ([], replicate n [])` – Probie May 01 '18 at 14:50
  • Do you want just want the same thing with triples? `foldr (\x (l1,l2,l3) -> (x:l2,l3,l1)) ([],[],[])`? I think I'm missing something. – Probie May 01 '18 at 14:56
  • `foldr (\x (l1,l2,l3) -> (x:l3,l1,l2)) ([],[],[]) [1..10]` then. By "missing something" I mean that I have no clue why you're asking the question. – Probie May 01 '18 at 15:02
1

Given a predicate p :: a -> Bool you can split on that using foldr as follows:

split :: (a -> Bool) -> [a] -> ([a],[a])
split p = foldr (\x (as, bs) -> if p x then (x:as, bs) else (as, x:bs)) ([],[])

For example:

Prelude> split (\x -> x `mod` 4 /= 0) [2,4,6,8,7]
([2,6,7],[4,8])
fxvdh
  • 147
  • 9