2

I wrote a function which cuts a list into half in every possible way. My problem is that I used the 'lenght' function so it can't work with infinite lists. I couldn't think of anything that actually fixed this. Any idea how could I solve this problem?

Example:

splitList "home"= [("","home"),("h","ome"),("ho","me"),("hom","e"),("home","")]

My code:

splitList :: [a] -> [([a],[a])]
splitList a = splitList' a

splitList' ::  [a] -> [([a],[a])]
splitList' a =  take ((length a)+1)  (splitList'' 0 a)

splitList'' :: Int -> [a] -> [([a],[a])]
splitList'' i a = (splitAt i a) : splitList'' (i+1) a 
3t893w
  • 297
  • 3
  • 5

1 Answers1

2

length a will get stuck in an infinite loop on an infinite list. You thus will need to recurse in another way. You can recurse on the list until you reach the end of the list, for example with:

splitList :: [a] -> [([a],[a])]
splitList [] = [([], [])]
splitList xa@(x:xs) = ([], xa) : map … (splitList xs)

here you need to fill in the part where for each tuple in splitList xs you prepend the first item of each 2-tuple with x.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555