rtulip / haystack

Haystack is a compiled, statically typed, stack-based language with opt-in variable assignment.
MIT License
25 stars 2 forks source link

Nicer Loops #145

Open rtulip opened 1 year ago

rtulip commented 1 year ago

Now that Haystack has interfaces, we can maybe start thinking about making loops nicer. In rust, a for loop looks like this:

let bar = vec![1, 2, 3];
for foo in bar {
    println!("foo: {foo}")
}

Which is really just syntactic sugar (or something close to) for:

let bar = vec![1, 2, 3];
{
    let iter = bar.into_iter();
    while let Some(foo) = iter.next() {
        println!("foo: {foo}")
    }
}

Going backwards, we could implement similar IntoIter and Iterator interfaces, which would let us write something like this:

interface IntoIter<T> {
    _: Iter
    fn Iter.into(T) -> [Iter] 
}

interface Iterator<T> {
    _: Item
    fn Iter.next(mut T) -> [Opt<Item> bool]
}

Vec.new::<u64> as [mut bar]
// populate bar
bar Iter.into as [it] {
    while *it Iter.next {
        Opt.unwrap as [foo]
        "foo: " print foo println
    } drop 
}

With some syntactic sugar of our own, we can get a for loop

Vec.new::<u64> as [bar]
// ...
for foo in bar {
    "foo:" print foo println
}