3 ms·
In a traditionally compiled language, currying doesn't provide varargs: the compiler still has to know how many parameters a function takes before it can be cal
by rwmj 14y ago
In a traditionally compiled language, currying doesn't provide varargs: the compiler still has to know how many parameters a function takes before it can be called. You cannot write `printf "%d" 1' expecting that at runtime printf is going to parse the string and read further arguments, because the compiler wouldn't know when printf can be called.
OCaml famously (or notoriously) hacks this knowledge into the compiler, so the compiler knows about format strings and parses them. This is nicely typesafe, but means you cannot use varargs in your own functions, and there are odd restrictions on the format string. (You can use the camlp4 preprocessor, or lists-as-parameters, to get around this).
- guard-of-terra 14y ago"the compiler still has to know how many parameters a function takes before it can be called" I guess it's better viewed as: type system has to figure out whether a consecutive currying/calling will return a scalar/function of zero arguments.
- chongli 14y agoHaskell has printf without using lists-as-parameters. It accomplishes this by doing some very clever type-level trickery. The key idea is in the recursive definition of this instance of PrintfType: instance (PrintfArg a, PrintfType r) => PrintfType (a -> r) where
- philsnow 14y agoYour snippet got cut off, care to paste the rest? I'm guessing it works by popping the format string and the first operand off the args, and then finding the first formatting escape in the format string and formatting it, then recurse.
- chongli 14y agoYeah, sorry. Here's the full snippet: instance (PrintfArg a, PrintfType r) => PrintfType (a -> r) where spr fmts args = \ a -> spr fmts (toUPrintf a : args) And spr is a polymorphic function of the type: spr :: String -> [UPrintf] -> t Essentially the way this works is that it recursively conses up a list of the arguments, calling toUPrintf on each.