0

A content question (not a homework question) from a Coursera course on programming languages (taught at U of Washington) - I'm getting no response on the Coursera forum....

Abridged code (variable 'cbs' is a list reference that is already defined before this):

 (* function to add a callback to the callback list *)
 onKeyEvent f = cbs := f :: (!cbs)

(* then, later, in the client code.... *)
val _ = onKeyEvent (fn _ => timesPressed := (!timesPressed) + 1)

Professor writes, "The 'val _ = e' idiom is common for executing an expression just for its side-effect, in this case registering a callback.

What I do not understand is why not just call the function above directly, as in:

onKeyEvent(fn _ => timesPressed := (!timesPressed) + 1)

Why call it by binding it to "_" ? Professor says this is a style thing, but it seems completely unnecessary and complicating.

Thanks for any feedback on this.

JayW
  • 23
  • 5
  • 1
    I ran some test code in the REPL. It seems SML does not like calling functions without assigning them first. If a function is defined and later called directly, like, "print '6' " the compiler thinks this statement is just a part of any previous statement and interprets the print function simply as "( )" (or, 'unit') which then does not make sense when directly following a prior line of code. So, the parser needs to see a 'val' keyword, and possibly a '=' for assignment before it understands that 'print' is a standalone function. So all functions must be called with assignment only?? – JayW Dec 26 '20 at 01:07
  • 2
    At the top level, a SML program is a sequence of top level declarations from the core & module languages (pedantically, I believe just the module language, but a core language declaration is treated as a strdec). As expressions (which function applications are) aren't declarations they cannot appear at the root of the program (by grammatical fiat). The REPL differs in that it allows an expression as a sugared form of `val it = e` where `e` is the provided expression. – kopecs Dec 26 '20 at 21:05

0 Answers0