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

后端 未结 13 1721
庸人自扰
庸人自扰 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:14

    ($) allows functions to be chained together without adding parentheses to control evaluation order:

    Prelude> head (tail "asdf")
    's'
    
    Prelude> head $ tail "asdf"
    's'
    

    The compose operator (.) creates a new function without specifying the arguments:

    Prelude> let second x = head $ tail x
    Prelude> second "asdf"
    's'
    
    Prelude> let second = head . tail
    Prelude> second "asdf"
    's'
    

    The example above is arguably illustrative, but doesn't really show the convenience of using composition. Here's another analogy:

    Prelude> let third x = head $ tail $ tail x
    Prelude> map third ["asdf", "qwer", "1234"]
    "de3"
    

    If we only use third once, we can avoid naming it by using a lambda:

    Prelude> map (\x -> head $ tail $ tail x) ["asdf", "qwer", "1234"]
    "de3"
    

    Finally, composition lets us avoid the lambda:

    Prelude> map (head . tail . tail) ["asdf", "qwer", "1234"]
    "de3"
    

提交回复
热议问题