[swift-evolution] Memoization for functions without parameters in enums

David Sweeris davesweeris at mac.com
Tue Apr 25 12:18:59 CDT 2017



Sent from my iPhone

> On Apr 25, 2017, at 06:44, Tierry Hörmann via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hi all
> 
> I discovered that memoization is currently a pain to implement when using functional programming.
> E.g. when implementing a lazy linked list, one obviously uses an enum to represent the data. But there is also a wrapper struct needed with lazy variables (especially a lazy property tail), as enums can not have stored properties. Here some example code of such a lazy linked list:
> 
> public struct LazyList<T> {
>     let root: LLE<T>
>     
>     init(_ root: LLE<T> = LLE<T>.End) {
>         self.root = root
>     }
>     
>     public var hd: T? {
>         get {return root.val()}
>     }
>     
>     
>     lazy private var tail: LLE<T> = self.root.tail()()
>     public var tl: LazyList<T> {
>         mutating get {
>             return LazyList<T>(tail)
>         }
>     }
> }
> 
> enum LLE<T> {
>     case End
>     indirect case Node(T, () -> LLE<T>, Int)
>     
>     func val() -> T? {
>         switch self {
>         case let .Node(v, _, _):
>             return v
>         default:
>             return nil
>         }
>     }
>     
>     func tail() -> () -> LLE<T> {
>         switch self {
>         case let .Node(_, tl, _):
>             return tl
>         default:
>             assert(false, "Can't call tail on empty list")
>             return {self}
>         }
>     }
> }
> 
> 
> In my opinion this isn’t optimal (and can also create bigger problems, e.g. when implementing count). But enums in swift are purely functional and therefore functions without parameters always return the same value in an enum, so storing the result of a function call with no parameters could in some situations give a great performance boost.
> Has this issue already been discussed? If yes, what was the outcome? And if no, I would suggest an additional keyword “memoizing” for functions without parameters in enums. Or maybe someone has a better idea, which would fit better inside the swift universe?

We've talked about "pure" functions (a prerequisite for memoization) a few times. Usually around the time we start talking about which definition of "pure" we want to use, someone will come by and say it's out of scope. IIRC, the last time it happened was after we started discussing Swift 4, so I'd guess it's still out of scope.

- Dave Sweeris 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170425/9684cdea/attachment.html>


More information about the swift-evolution mailing list