6

I want to write a function point-free in haskell, to keep things simple lets say I want to make this function:

maxmin :: Ord a => a -> a -> a -> a
maxmin a b c = max a (min b c)

I can improve this to

maxmin a b = (max a) . (min b)

but is there any way to get rid of a and b?

Erik Henriksson
  • 737
  • 1
  • 6
  • 13
  • 8
    Point-free is a code *style*, and as such should only be used when it improves readability; the cases where point-free notation compiles differently (because of inlining) are not something you have to worry about in general (think about that after profiling). In your case, I'd say point-free doesn't help; renaming `maxmin` to `constrainTo` would be a much more expressive change, for example. – David Nov 20 '12 at 14:39

2 Answers2

10

I wouldn't say this is simplier but here you go:

maxmin :: Ord a => a -> a -> a -> a                                             
maxmin = (. min) . (.) . max 

(Generated with pl tool from lambdabot http://www.haskell.org/haskellwiki/Pointfree)

lambdabot> pl maxmin a b c = max a (min b c)
maxmin = (. min) . (.) . max
applicative_functor
  • 4,926
  • 2
  • 23
  • 34
4

You just use the "three laws of sections" for that,

(a `op` b) = (a `op`) b = (`op` b) a = op a b

so that

import Control.Arrow

maxmin a b = (max a) . (min b)
           = (.) (max a) (min b)
           = uncurry (.) (max a, min b)
           = uncurry (.) . (max *** min) $ (a, b)
           = curry (uncurry (.) . (max *** min)) a b

which is not too readable either. :)

Community
  • 1
  • 1
Will Ness
  • 70,110
  • 9
  • 98
  • 181