Reputation: 435
I'm very new to Haskell and I'm trying to understand these basic lines of code. I have a main module that's very simple:
main = do
words <- readFile "test.txt"
putStrLn $ reverseCharacters words
where reverseCharacters
is defined in another module that I have:
reverseCharacters :: String -> String
reverseCharacters x = reverse x
What I am having trouble understanding is why the $
needs to be there. I've read previous posts and looked it up and I'm still having difficulty understanding this. Any help would be greatly appreciated.
Upvotes: 1
Views: 116
Reputation: 71495
$
is an operator, just like +
. What it does is treat its first argument (the expression on the left) as a function, and apply it to its second argument (the expression on the right).
So in this case putStrLn $ reverseCharacters words
is equivalent to putStrLn (reverseCharacters words)
. It needs to be there because function application is left associative, so using no $
or parentheses like putStrLn reverseCharacters words
would be equivalent to parenthesising this way (putStrLn reverseCharacters) words
, which doesn't work (we can't apply putStrLn
to reverseCharacters
[something of type String -> String
], and even if we could we can't apply the result of putStrLn
to words
[something of type String
]).
The $
operator is just another way of explicitly "grouping" the words than using parentheses; because it's an infix operator it forces a "split" in the expression (and because it's a very low precedence infix operator, it works even if the things on the left or right are using other infix operators).
Upvotes: 10