Search code examples
haskellsyntaxfunction-compositiondollar-sign

Chaining two parentheses together using $ operator


I have this function:

min (max 10 20) (max 30 40)

I can rewrite this as:

min (max 10 20) $ max 30 40

But is there also a way to resolve these last parentheses?

Not as if this wasn't good enough, but I just can't let the thought go, that there must be some way to do this...


Solution

  • It would be nice to be able to write:

    min $ max 10 20 $ max 30 40
    

    However, this wouldn't work because $ is right associative:

    Prelude> :info $
    ($) :: (a -> b) -> a -> b   -- Defined in ‘GHC.Base’
    infixr 0 $
    

    Hence, the expression is disambiguated as:

    min ((max 10 20) max 30 40)
    

    Indeed, it would make more sense for $ to be left associative. However, we can't simply make $ left associative because it might break existing code. Nevertheless, you could define a new operator:

    infixl 0 %
    
    (%) :: (a -> b) -> a -> b
    f % x = f x
    
    main = print (min % max 10 20 % max 30 40)
    

    The % symbol is right next to the $ symbol on a US keyboard.