diff options
| author | Cliff Click <cliffc@acm.org> | 2024-11-01 10:01:20 -0700 |
|---|---|---|
| committer | Cliff Click <cliffc@acm.org> | 2024-11-23 09:03:20 -0800 |
| commit | 59fb2c02e08b9bf577f2dedfabd290cb6e00e016 (patch) | |
| tree | 927e4c50f02d51a55701f69ab15463fa5d59d019 /chapter17/README.md | |
| parent | dedfcd5380ce4cd71b0e68047de1e76b8c04cfb4 (diff) | |
| download | Simple-59fb2c02e08b9bf577f2dedfabd290cb6e00e016.tar.gz Simple-59fb2c02e08b9bf577f2dedfabd290cb6e00e016.zip | |
Some ideas on functions
Diffstat (limited to 'chapter17/README.md')
| -rw-r--r-- | chapter17/README.md | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/chapter17/README.md b/chapter17/README.md index e0e71539..bedce38b 100644 --- a/chapter17/README.md +++ b/chapter17/README.md @@ -1,3 +1,62 @@ # Chapter 17: Functions +Some thinking on function syntax: +Function Types: +``` +{ argtype, argtype, ... -> rettype } +``` + +Leading `{` character denotes the start of a function or function type. + +Functions are normal variables and assigned the same way: + +```functiontype var = function-typed-expr``` + +Functions themselves using the same syntax with as types, but filled in: + +``` +{ int x, int y -> + sqrt(x*x+y*y); +} +``` + +Used in a declaration statement: +``` +// TYPE VAR = EXPR +{flt,flt->flt} dist = { flt x, flt y -> + sqrt(x*x+y*y); +} +``` + +Because it gets clunky to write the function type, and because it can be +directly inferred from forwards-flow analysis (not even HM) which we're already +doing at parse-time, we add a new variable declaration syntax: "var" - for +auto-inferring variable types. Not allowed in function headers. +``` +var dist = { flt x, flt y -> sqrt(x*x*,y*y); } +``` + +`var` can be used for normal variables as well: + +``` +// Newtons approximation to the square root +var sqrt = { flt x -> + var guess = x*x/2; + while( 1 ) { + var next = (x/guess + guess)/2; + if( next == guess ) break; + guess = next; + } + guess; +} +``` + +When inferring pointer types, it will use the `glb` of the initial expression +type, which may not be what you want: + +``` +struct LLI { LLI? next; int i; }; +var head = LLI(); // Want this declared not-null, but GLB will allow null +head = null; // Allowed +```
\ No newline at end of file |
