Google News
logo
Haskell - Interview Questions
Explain what is the difference between $ (dollar sign) and . (dot) ?
The dollar sign (`$`) and the dot (`.`) are both operators in Haskell, but they serve different purposes and have distinct effects on function application and composition.

1. The Dollar Sign Operator ($) :
   * The dollar sign operator is used for function application. It allows you to avoid using parentheses and helps clarify the order of evaluation in complex expressions.
   * It has the lowest precedence of any infix operator, which means it binds less tightly than any other operator. This allows it to be used to apply a function to its argument without the need for parentheses.
   * The `$` operator has the following type signature: `($) :: (a -> b) -> a -> b`.
   * The expression `f $ x` is equivalent to `f x`.
   * The primary purpose of the `$` operator is to eliminate the need for explicit parentheses when applying a function to an argument or composing functions.

   For example:
   -- Without using $
   result1 = sin (cos (sqrt 2))

   -- Using $
   result2 = sin $ cos $ sqrt 2​

   In the above example, `result1` and `result2` are equivalent. The `$` operator allows for a more concise and readable expression by avoiding nested parentheses.
2. The Dot Operator (Composition) :
   * The dot operator is used for function composition. It allows you to combine functions and create new functions by chaining them together.
   * It has a higher precedence than most operators, including the dollar sign operator.
   * The dot operator has the following type signature: `(.) :: (b -> c) -> (a -> b) -> a -> c`.
   * The expression `(f . g) x` is equivalent to `f (g x)`.
   * The primary purpose of the dot operator is to enable the composition of functions, where the output of one function is passed as the input to another function.

   For example:
   add1 :: Int -> Int
   add1 x = x + 1

   double :: Int -> Int
   double x = x * 2

   -- Without using .
   result3 = double (add1 5)

   -- Using .
   result4 = double . add1 $ 5​

   In the above example, `result3` and `result4` are equivalent. The dot operator allows for a more elegant expression by composing the `add1` and `double` functions.
Advertisement