Question

I tried the $ operator and came to a weird point where I don't understand what is happening.

f = double $ 3+4

but this does not

f xs = xs !! $ length xs - 1

Can the operator $ only appear after function names and not after operators? If so is there a way to write the following function without the parenthesis

f xs = xs !! (length xs - 1)
Was it helpful?

Solution

You can't have two operators next to each other, it's invalid syntax. This holds true for all operators. So xs !! $ length xs - 1 just will not work. There isn't really a good way to get rid of the parens in that statement without resorting to some tricks that aren't worth it and make the code less readable.


The $ operator does not have to appear after function names, though, you can do

> let add x y = x + y
> add 1 $ add 2 $ add 3 4

OTHER TIPS

Haskell infix notation is problematic, avoid it like this

f xs = (!!) xs $ length xs - 1

The brackets turn an infix operator into a prefix function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top