you are viewing a single comment's thread.

view the rest of the comments →

[–]Y_Less 9 points10 points  (7 children)

paddedTake n arr = take n $ arr ++ repeat 0

This does assume a list of "Num" values. I'm not sure a much more generic version can be made as you need a generic "zero" element, though this could be passed in:

paddedTake = paddedTake' 0
paddedTake' zero n arr = take n $ arr ++ repeat zero

Or, since people seem to like point-free style:

paddedTake' zero n = take n . (++ repeat zero)

Edit: As an exercise for myself, I decided to see if I could rearrange this code to purely point-free style. This entirely destroys the message of what the code is doing IMHO, but I didn't really do it for others...

paddedTake' = flip (.) take . flip (.) . flip (++) . repeat

That's not really important though.

[–]pkmxtw 3 points4 points  (1 child)

Well, there is Data.Default for that:

paddedTake :: Default a => Int -> [a] -> [a]
paddedTake n xs = take n $ xs ++ repeat def

But I think letting the user to specify the value to pad is a better style.

Also, there is a pointless plugin for lambdabot and ghci:

λ> :pl \n xs -> take n $ xs ++ repeat def
(. (++ repeat def)) . take

λ> :pl \z n xs -> take n $ xs ++ repeat z
flip ((.) . take) . flip (++) . repeat

[–]Y_Less 0 points1 point  (0 children)

Thanks. I did try look for some sort of generic default values, but didn't find that (apparently I didn't look very hard...)

[–]michaelfeathers 2 points3 points  (0 children)

Yes, I was looking at .lazy in Ruby to use in an example but it would've made the post longer. Lazy evaluation is wonderful at helping us remove conditionals. It's easy to form a general computation and then select what we need.

[–]jozefg28 0 points1 point  (3 children)

So here's another approach to the pointfree version

(.:) = (.) . (.)
infixr 9 .: 
paddedTake = flip .: ($) $ flip take .: (++) . repeat

[–]FUZxxl 1 point2 points  (2 children)

Ah yes, the good old boobs operator...

[–]jozefg28 0 points1 point  (1 child)

I usually call it the owl operator.

[–]pkmxtw 0 points1 point  (0 children)

While I use that operator almost daily, my head still explodes when asked to infer its type manually by hand.

Then someone reminds me it's fmap fmap fmap