robrix / Prelude

Swift µframework of simple functional programming tools
MIT License
409 stars 26 forks source link

const overload accepting a closure for memoized lazy evaluation #32

Open robrix opened 9 years ago

robrix commented 9 years ago

I think const might be more useful if it were marked as @autoclosure(escaping). As it is, you can’t use it for any kind of effectful case analysis because effects occur regardless of the branch taken, which defeats the purpose of using case analysis for effects.

robrix commented 9 years ago

This would be very much in the spirit of Haskell, since Haskell is lazily-evaluated by default.

jspahrsummers commented 9 years ago

The semantics of @autoclosure(escaping) are non-obvious to most folks, and it doesn't help that you'd have to read the documentation to realize that it automatically closes over your value.

I think escaping autoclosures are an anti-feature, and their use should be discouraged. If you want to support lazy evaluation, accept an explicit closure.

robrix commented 9 years ago

That’d look like so:

fooBarQuux.analysis(
    ifFoo: const(0),
    ifBar: const { ++x },
    ifQuux: { $0 + $1 })

Yeah, I agree—that’s much less problematic.

robrix commented 9 years ago

It’s hardly a constant unless it memoizes as well. I think that lines up nicely with this.