Haskell - wrapping and expanding newtype covers - is there an easier way?

I am writing a pad function that takes a list and overlays it to a specific size. I tried 2 implementations:

 pad :: Monoid a => Int -> [a] -> [a] pad len list = replicate (len - length list) mempty ++ list 

and

 pad :: Int -> a -> [a] -> [a] pad len value list = replicate (len - length list) value ++ list 

The first is similar to the logical use of Monoid , but calling it with lists of integers (or everything that is Monoid several ways) is a pain:

 (fmap getSum) <$> pad 8 <$> (fmap Sum) <$> [1,2,3] 

Actually, I am not opposed to additional text input, but it does not even convey meaning very well. How to implement this function?

+4
source share
1 answer

I would probably use your second example. Adding a Monoid constraint to use mempty as the default value is redundant. It also sends an incorrect message to users of this function, which may be confused by what you need mappend if you do not. They would also need to instantiate newtype and Monoid if they wanted to use a different value.

Instead, consider changing the order of the arguments so that the first value comes out. Then you can simply apply it partially when you need to populate a lot of lists with the same value. You can also restore the first version with pad mempty if you need it.

+10
source

Source: https://habr.com/ru/post/1483467/


All Articles