1

When I have a function

func :: Int -> Int -> [[a]]
func a b = func' a ++ func' b

where

func' :: Int -> [[a]],

what is a good possibility to avoid the (++)?

user2840552
  • 23
  • 1
  • 5

3 Answers3

6

Sequence is an alternative to lists which has many operation implemented efficiently.

Nicolas
  • 24,509
  • 5
  • 60
  • 66
Satvik
  • 11,238
  • 1
  • 38
  • 46
2

There is a general "difference list" technique for (++) elimination by rewriting a function to use extra argument such that f a b == g a ++ b.

You can see it used e.g. in

In your case this means rewriting func to incorporate the func' functionality by essentially inlining the (++), e.g.:

func :: Int -> Int -> [[a]]
func a b = go a 1 where 
  go _ _ = _ : _
  go _ _ = _ : _            -- replicate func' code, except
  go _ 1 = {- [] -} go b 0  -- the base case 
  go _ 0 = []               
Community
  • 1
  • 1
Will Ness
  • 70,110
  • 9
  • 98
  • 181
0

If you want to stick to List, you can use join (>>=) like so: func a b = [a, b] >>= func'.

Nicolas
  • 24,509
  • 5
  • 60
  • 66
  • 1
    I didn't notice the comment about complexity. With lazy evaluation neither (++) nor >>= are costly. – Nicolas Oct 14 '13 at 08:50