vasyok03
vasyok03

Reputation: 21

Haskell make groupBy shorter

groupBy(\x y -> foo x == foo y)(sortOn foo a)

How to make this code shorter? (\x y -> foo x == foo y)- I think it's possible to make this part shorter

I have only one Import

import Data.List

Upvotes: 0

Views: 86

Answers (4)

DDub
DDub

Reputation: 3924

If you want to sacrifice readability for two more characters, you can go the pointfree route and replace \x y -> foo x == foo y with:

(. foo) . (==) . foo

Sometimes it's fun to play around with http://pointfree.io/ :).

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You can also make use of the extra package [Hackage] and work with groupOn :: Eq b => (a -> b) -> [a] -> [[a]]:

import Data.List.Extra(groupOn)

groupOn foo (sortOn foo a)

Upvotes: 1

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

You can make it a little bit shorter by using the on combinator:

groupBy ((==) `on` foo) (sortOn foo a)

But you'd have to import it from Data.Function, which makes the overall amount of code greater.

Upvotes: 4

chepner
chepner

Reputation: 531205

Use Data.Function.on:

groupBy ((==) `on` foo) (sortOn foo a)

Upvotes: 4

Related Questions