[Haskell-cafe] What is the role of $!?
Andrew Coppin
andrewcoppin at btinternet.com
Sun Nov 18 05:05:35 EST 2007
PR Stanley wrote:
> Hi
> okay, so $! is a bit like $ i.e. the equivalent of putting parentheses
> around the righthand expression. I'm still not sure of the difference
> between $ and $!. Maybe it's because I don't understand the meaning of
> "strict application". While we're on the subject, what's meant by
> Haskell being a non-strict language?
> Cheers
> Paul
It simply means in Haskell, if you call a function, that function is not
executed until you try to do something with the result.
"f $ x + y" is like "f (x + y)". The value of "x + y" will only actually
be calculated if "f" tries to examine its value. For example,
f1 x = 7
f2 x = if x == 0 then 0 else 1
The "f1" function ignores "x" and always returns "7". If you did "f1 $ x
+ y", then "x + y" would never ever be calculated at all.
However, "f2" looks at "x" to see if it's 0. So if you do "f2 $ x + y",
the "x + y" part will be calculated.
"f $! x + y" is just like "f $ x + y", except that "x + y" will be
calculated *before* "f" is called - regardless of whether "f" does
anything with this data.
The usual reason for doing this is to avoid large unevaluated
expressions accumulating inside a program loop - e.g., if you were
calculating a total, you probably want the "total" variable to actually
contain the total rather than just a big expression like "1 + 2 + 3 +
...", so you could use $! to force the total to actually be calculated
before starting the next loop [which will be a recursive function call].
Make any sense?
PS. There is a technical distinction between the terms "lazy" and
"non-strict", and also the opposite terms "eger" and "strict". I
couldn't tell you what that is.
More information about the Haskell-Cafe
mailing list