What is the difference between . (dot) and $ (dollar sign)?

后端 未结 13 1723
庸人自扰
庸人自扰 2020-11-22 04:57

What is the difference between the dot (.) and the dollar sign ($)?

As I understand it, they are both syntactic sugar for not needing to us

相关标签:
13条回答
  • 2020-11-22 05:24

    The most important part about $ is that it has the lowest operator precedence.

    If you type info you'll see this:

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

    This tells us it is an infix operator with right-associativity that has the lowest possible precedence. Normal function application is left-associative and has highest precedence (10). So $ is something of the opposite.

    So then we use it where normal function application or using () doesn't work.

    So, for example, this works:

    λ> head . sort $ "example"
    λ> e
    

    but this does not:

    λ> head . sort "example"
    

    because . has lower precedence than sort and the type of (sort "example") is [Char]

    λ> :type (sort "example")
    (sort "example") :: [Char]
    

    But . expects two functions and there isn't a nice short way to do this because of the order of operations of sort and .

    0 讨论(0)
提交回复
热议问题