-1

I'm trying to do SICP exercise 2.6 in swift which is about church numerals

The zero is defined in scheme as

(define zero (lambda (f) (lambda (x) x)))

converted to swift closure I think is

let zeroR = {(x:Int)->Int in return x}

let zero = {(f:(Int)->Int)->(Int)->Int in return zeroR}

But the problem is the definition of add-1 which is in scheme

(define (add-1 n)
    (lambda (f) (lambda (x) (f ((n f) x)))))

I can't convert this to swift closure version yet. Some idea?

Thanks.

dopcn
  • 4,218
  • 3
  • 23
  • 32
  • so you basically want a recursive lambda expression? – luk2302 Dec 29 '15 at 17:03
  • Here is another question about implementing Church encoding in Swift: http://stackoverflow.com/questions/33597144/swift-higher-order-function-church-pair-aka-cons-with-generic-parameter-types. I don't know much about that stuff, but if I understand it correctly, it is currently not possible in Swift. – Martin R Dec 29 '15 at 17:09
  • @luk2302 There is no recursion. – molbdnilo Dec 29 '15 at 17:53
  • There is no recursion in closures...there is recursion in functions. OP may have to write these exercises as functions instead of closures. – Aaron Rasmussen Dec 29 '15 at 18:00

1 Answers1

0

I wrote the following two functions for zero and add_1:

func zero<T>(f: T -> T) -> T -> T {
    return { x in x }
}

func add_1<T>(n: (T -> T) -> T -> T ) -> (T -> T) -> T -> T  {
    return { f in
        return { x in 
            return f(n(f)(x))
        }
    }
}

Now you can define one, for example, in terms of zero and add_1:

func one<T>(f: T -> T) -> T -> T {
    return add_1(zero)(f)
}

Perhaps something like that is along the lines of what you are looking for?

And if you really want to use closures, it would look something like this, but it loses the ability to work with generics:

let _zero: (Int -> Int) -> Int -> Int = { _ in
    return { x in x }
}

let _add_1: ((Int -> Int) -> Int -> Int) -> (Int -> Int) -> Int -> Int = { n in
    return { f in
        return { x in
            return f(n(f)(x))
        }
    }
}
Aaron Rasmussen
  • 13,082
  • 3
  • 42
  • 43