Eryk Ciepiela
Eryk Ciepiela

Reputation: 195

List instance of semigroup mappeding respective pairs of elements

I am looking for most common Haskell library that introduces [a] wrapper that instantiates Semigroup by delegating mappending to its elements in the similar way to:

newtype SList a = SList { slist :: [a] } 

instance Semigroup a => Semigroup (SList a) where
    l1 <> l2 = SList $ foldl1 (<>) <$> transpose [slist l1, slist l2]

For example, SList [a,b,c] <> SList [d,e,f,g] would evaluate to SList [a <> d, b <> e, c <> f, g].

To my surprise I couldn't found any in Prelude nor other most popular libraries. Why is that?

Upvotes: 2

Views: 86

Answers (1)

Not a wrapper type, but a different function that does that on regular lists: salign from semialign's Data.Semialign. You can either call it directly or implement SList in terms of it:

import Data.Semialign (salign)
instance Semigroup a => Semigroup (SList a) where
    SList l1 <> SList l2 = SList (salign l1 l2)

Upvotes: 3

Related Questions