Skip to content

Instantly share code, notes, and snippets.

@hishamhm
Last active October 3, 2015 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hishamhm/d4c4f4da44dc5042d522 to your computer and use it in GitHub Desktop.
Save hishamhm/d4c4f4da44dc5042d522 to your computer and use it in GitHub Desktop.
Are there inference systems out there smart enough to know that line 5 can't fail?
function foo(tbl)
local var: string? = tbl.field -- string or nil
local function f(x)
print(x .. var) -- var must be string!
end
if type(var) == "string" then
f("hello, ") -- f is only called where var is known to be string
end
end
@mascarenhas
Copy link

For traditional type inference (based on solving constraints among types), no. Type inference based on flow analysis for sets of abstract values is able to do that, but has its own issues. A recent example of this approach is http://cs.brown.edu/~sk/Publications/Papers/Published/gsk-flow-typing-theory/ (and maybe Facebook Flow, the documentation is sparse on how it works, and I haven't read the source).

If you just want your example to compile, you can lift "var" to be a parameter of f, with type string. :-)

@Johnicholas
Copy link

I am not at all certain that you need flow typing, but it does look cool. Here's another link: http://whiley.org/guide/typing/flow-typing/

I think Benjamin Pierce calls the control flow construct for destructing a sum type "case". http://www.cis.upenn.edu/~bcpierce/sf/current/MoreStlc.html

If you were willing to do the lambda lifting transformation to get into first-order form, and also recognize "if type(var) == " as a kind of "case" statement, it would be simply typable, no?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment