Search code examples
listhaskellpad

Left pad a Haskell list


If I wanted to right-pad a Haskell list of integers, I could do something like the following:

rpad m xs = take m $ xs ++ repeat 0

There would be no need to get the length of the list. I think it would be quite performant.

Is there a similar way I could definte lpad, padding the list on the left, without incurring the cost of counting the length, etc. ?


Solution

  • So the first thing worth saying is, don't worry too much about the nitty-gritty of performance. This code is unlikely to be sitting in the proverbial 20% of your code which takes up 80% of the running time.

    With that said, where does performance really matter, here? It matters if m is small while length xs is huge or infinite. I mean, it would also be nice to get good performance if m is large (as you have with rpad, where if you process only the first k items of the list you only do k work for some k << m), but of course the very problem description requires that you potentially do m work to see the top result. (If you're provided an infinite list you need to peek at m items to even know whether to return 0 for the first element.)

    In that case, you really want to zero-pad take m xs instead of xs. That's the entire trick:

    lpad m xs = replicate (m - length ys) 0 ++ ys
        where ys = take m xs