Skip to content

Instantly share code, notes, and snippets.

@rsp
Last active November 29, 2017 13:59
Show Gist options
  • Save rsp/da7445befa774b6cf63863cc1ed4e036 to your computer and use it in GitHub Desktop.
Save rsp/da7445befa774b6cf63863cc1ed4e036 to your computer and use it in GitHub Desktop.
inFullMobile Language Wars: Round 1 - Swift Solution 1 - full code by @mikchmie-ifm - See: https://gist.github.com/rsp/d8bdbafa09f24f99eebc8ed60fe205c8
import Foundation
func inc(_ num: Int) -> Int {
return num + 1
}
func count(_ foo: @escaping (@escaping (Int) -> Int) -> (Int) -> Int) -> Int {
return foo(inc(_:))(0)
}
func f(_ foo: @escaping (@escaping (Int) -> Int) -> (Int) -> Int) -> (@escaping (Int) -> Int) -> (Int) -> Int {
return { op in
return { num in
let times = foo({ x in x + 1 })(0) - 1
return (0..<times).reduce(num, { result, _ in op(result) })
}
}
}
// Applies x() 1 time:
func input1(_ x: @escaping (Int) -> Int) -> (Int) -> Int {
return { y in
return x(y)
}
}
// Applies x() 2 times:
func input2(_ x: @escaping (Int) -> Int) -> (Int) -> Int {
return { y in
return x(x(y))
}
}
// Applies x() 10 times:
func input3(_ x: @escaping (Int) -> Int) -> (Int) -> Int {
return { y in
return x(x(x(x(x(x(x(x(x(x(y))))))))))
}
}
// Applies x() 100 times:
func input4(_ x: @escaping (Int) -> Int) -> (Int) -> Int {
return input3(input3(x));
}
// Applies x() 1000 times:
func input5(_ x: @escaping (Int) -> Int) -> (Int) -> Int {
return input3(input4(x));
}
count(input1(_:)) == 1
count(input2(_:)) == 2
count(input3(_:)) == 10
count(input4(_:)) == 100
count(input5(_:)) == 1000
count(input1(_:)) == count(f(input1(_:))) + 1
count(input2(_:)) == count(f(input2(_:))) + 1
count(input3(_:)) == count(f(input3(_:))) + 1
count(input4(_:)) == count(f(input4(_:))) + 1
count(input5(_:)) == count(f(input5(_:))) + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment