Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is whitespace either used as a function application operator or a word separator

Tags:

haskell

How does outermost evaluation work on an application of a curried function? says:

in Haskell, whitespace is an operator: it applies the lhs function to the rhs argument.

Is it true? I can't find it in documents.

When Haskell compiler lexical analyzing a Haskell program, is a whitespace recognized as either a function application operator or a token separator?

like image 564
Tim Avatar asked Jul 15 '19 01:07

Tim


Video Answer


2 Answers

The white space in most cases is "function application", meaning apply the function of the right, to the argument to the left, just like the ($) operator, but it can be used to be more clear on your code, some examples:

plusOne = (1 +)

you can either do

plusOne 2

or

plusOne $ 2

:t ($)
($) :: (a -> b) -> a -> b

I forgot a usefull example:

imagine you want to filter the greater than 3, but before you want to add one to each element:

filter (>3) $ map plusOne [1,2,3,4]

That will compile, but this wont:

filter (>3) map plusOne [1,2,3,4]

But in other cases, is not function application, like the other @bradrn answer or @Daniel warner comment just shows.

like image 21
A Monad is a Monoid Avatar answered Oct 24 '22 08:10

A Monad is a Monoid


I’ve never heard anyone say that whitespace is an operator before. I suppose you could consider it to be an operator in the context of a function application, but in most contexts it is not an operator. For instance, I don’t see any way to consider whitespace as an operator in the following code sample, where whitespace is used only to separate tokens:

module Main where

x = "test 1"
y = "test 2"

main = do
    (z : zs) <- getLine
    putStrLn $ z : (x ++ y ++ zs)

It seems fairly obvious here that whitespace is acting purely as a token separator. The apparent ‘operator-ness’ in something like f x y z can be best thought of as saying that if two values are placed next to each other, the second is applied to the first. For instance, putStrLn"xxx" and putStrLn "xxx" both apply "xxx" to putStrLn; the space is completely irrelevant.

EDIT: In a comment, @DanielWagner provided two great examples. Firstly, (f)x is the same as f x, yet has no whitespace; here we see confirmation that the space is acting purely as a token separator, so can be replaced by a bracket (which also separates tokens) without any impact on the lexemes of the expression. Secondly, f {x=y} does not apply {x=y} to f, but rather uses record syntax to create a new record based on f; again, we can remove the space to get f{x=y}, which does an equally good job of separating the lexemes.

like image 94
bradrn Avatar answered Oct 24 '22 07:10

bradrn