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

Tierry Hörmann tierryhoermann96 at gmx.ch
Tue Apr 25 08:44:59 CDT 2017


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?

Greetings
Tierry Hoermann
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170425/20669891/attachment.html>


More information about the swift-evolution mailing list