grain-lang / grain

The Grain compiler toolchain and CLI. Home of the modern web staple. 🌾
https://grain-lang.org/
GNU Lesser General Public License v3.0
3.22k stars 115 forks source link

Support recursive data bindings #97

Open ospencer opened 4 years ago

ospencer commented 4 years ago

Statements like let rec ones = [1, ...ones] should be allowed. This expression should result a list containing a head of the element 1, and a tail of that same list.

96 was done to address this as a bug.

Additional info: While in theory this could work with minimal code change, it doesn't because we currently create lists as the result of function calls. If we just used the normal data constructors, it would be fairly straightforward to do the proper backpatching, but pervasives.gr is currently loaded as an external module instead of being injected directly into the program, and thus the data constructors are brought in as functions. Maybe the list cons function can be optimized into a normal data construction?

phated commented 2 years ago

I assume this and #989 go hand-in-hand?

spotandjake commented 5 months ago

This would require some pretty big changes to the List library too wouldn't it? as any function like List.length, or List.forEach would just recurse infinitely?

also wondering the actual usefulness of being able todo this in the first place.

ospencer commented 5 months ago

No, we wouldn't need to change the List library. Recursing infinitely is the correct behavior.

It's shockingly more useful than you might think—for lists in particular, you might have programs that only ever operate on the head of a list. If you never wanted it to end, and return 1 forever, this would be a way to do that. You'll also want to think beyond lists and think about some cyclic data structures like cyclic graphs. Instead of having to use mutable fields to create a cyclic structure, you could keep it immutable by having the compiler generate the structure for you, with types that are actually representative of the data structure you want.

I assume this and https://github.com/grain-lang/grain/issues/989 go hand-in-hand?

Yes, but this would not be an issue once we move to wasm GC.