2 ms·
Here's my Forth version of the quadratic equation from elsewhere in this thread; it ends up being six lines instead of three, but I don't think that's excessive
by kragen 16y ago
Here's my Forth version of the quadratic equation from elsewhere in this thread; it ends up being six lines instead of three, but I don't think that's excessive:
variable a variable b variable c fvariable discriminant
: b^2 b @ dup * ; : 4ac 4 a @ c @ * * ; : s>f s>d d>f ;
: -b b @ negate s>f ; : /2a a @ 2* s>f f/ ; : f. f>d d. ;
: quadeq c ! b ! a ! b^2 4ac - s>f fsqrt discriminant f!
-b discriminant f@ f+ /2a
-b discriminant f@ f- /2a ;
I agree that the Python version is a lot clearer and less bug-prone, but I don't agree that this is extremely difficult to do without local variables. Forth-style global variables work fine, because the function isn't recursive. They're just bug-prone, that's all.
But they're much less bug-prone in Forth than in, say, C. I'm too sleepy to write in any detail about the aspects of Forth that lead me to this conclusion right now; they have to do with what Forth does with multiple definitions with the same name, with wordlists, and with layout. Suffice it to say that I'm no Forth advocate, but I do find it fascinating.