Functional programming fans, a challenge:

Here are two problems I've needed to solve lately where I don't see any reasonable way to do them with your average set of basic functional tools and immutable data, and instead I've ended up having to write very procedural loops-and-mutable-arrays type of code.

That code is generally not very satisfying to look at, but I just don't know any other reasonable solution, so, I'd love to hear how you would solve these:

1. Given a list like: [(1, a), (2, a), (3, a), (4, b), (6, b), (9, c)], transform it into:

[([1, 2, 3], a), ([4, 6], b), ([9], c)]

@WAHa_06x36
This is straight-forward enough in Haskell:

groupSnd :: Eq t => [(a, t)] -> [([a], t)]
groupSnd = map f . groupBy (\x y -> snd x == snd y)
where f group = (map fst group, snd $ head group)

@cthulahoops That fails the requirement I forgot and put in a later reply, I think?

Follow

@WAHa_06x36 I'm not seeing that. Unless you mean that ordering? In which case it's fine.

@WAHa_06x36
*Main> groupSnd [(1, 'a'), (2, 'b'), (3, 'a')]
[([1],'a'),([2],'b'),([3],'a')]

Not quite unchanged, but the type of the function would be weird if it was.

Sign in to participate in the conversation
Mastodon

A mastodon instance for anyone who likes green, purple, any colour that can be mixed from green or purple, or any colour that can be used to mix green or purple.

Just a personal instance to experiment with Mastodon.