Avatar
まず、↓の魔法の extension を用意して prefix func +(string: String) { print(string) }
9:31 AM
for n in 1...20 { let inTypes = (1...n).map { "T\($0)" } let commaSeparated = inTypes.joined(separator: ", ") let arrowSeparated = inTypes.map { "(\($0))" }.joined(separator: " -> ") let nestedClosuresBegin = inTypes.map { "{ \($0.lowercased()) in " }.joined() let nestedClosuresEnd = (1...n).map { _ in " }" }.joined() +""" public func curry<\(commaSeparated), R>(_ f: @escaping (\(commaSeparated)) -> R) -> \(arrowSeparated) -> R { return \(nestedClosuresBegin)f(\(commaSeparated.lowercased()))\(nestedClosuresEnd) } """ }
9:31 AM
swift ファイルとして実行可能
9:32 AM
↓実行結果 public func curry<T1, R>(_ f: @escaping (T1) -> R) -> (T1) -> R { return { t1 in f(t1) } } public func curry<T1, T2, R>(_ f: @escaping (T1, T2) -> R) -> (T1) -> (T2) -> R { return { t1 in { t2 in f(t1, t2) } } } public func curry<T1, T2, T3, R>(_ f: @escaping (T1, T2, T3) -> R) -> (T1) -> (T2) -> (T3) -> R { return { t1 in { t2 in { t3 in f(t1, t2, t3) } } } } public func curry<T1, T2, T3, T4, R>(_ f: @escaping (T1, T2, T3, T4) -> R) -> (T1) -> (T2) -> (T3) -> (T4) -> R { return { t1 in { t2 in { t3 in { t4 in f(t1, t2, t3, t4) } } } } }