What are some of your favorite “useful” Haskell oneliners? There are some really well-known elegant ones such as the lazy fibonacci sequence:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
But I don’t need that sequence often in my day job…
So one I particularly like is when you have a HashMap with Maybe a values. Data.HashMap.Strict does not provide a catMaybes to throw away the Nothings, but you can use:
HMS.mapMaybe id
Which is a really cool example of how the id function is useful!
-- | Helper-Function for pipelines with 2 input-variables.
-- Turns g :: c -> d and f :: a -> b -> c into
-- g ... f :: a -> b -> d
--
-- Useful for chaining:
-- a . b . c ... d
infixl 8 ...
(...) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
(...) = (.).(.)
It’s really a mouthful, but it gives me a custom environment with whatever packages I need straightaway, without needing to create a cabal or stack project or worry about cabal hell.
One of my favorite one-liners is the default implementation of the foldr function using foldMap.
foldr f z t = appEndo (foldMap (Endo . f) t) z
When I was learning Haskell it was really strange to me that in order to implement a Foldable instance it’s enough to implement either foldMap or foldr. The default implementation of foldMap via foldr is quite obvious, however it was completely unclear how to implement foldr having only foldMap. Now it makes sense, of course, and the solution is nice
@sjakobi@jhenahan
The following are a bit made up examples or might tell more about design issues:
something like bucket sort for certain prefix length of e.g. texts, and each bucket sorted then by length
histogram interval handling for more complex types (this is somewhat similar to the previous one)
a record with values and functions (and e.g. the equality is based on function similarity and length on values)
Each of the above probably need own-defined instances instead of stock defined ones for Eq, Foldable and/or Ord. E.g. comparing functions is hard but defining and using comparable names for functions helps etc.