Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- // High Order Function: Implementing Map, Filter, Reduce
- /* Map */
- func Map<T, U>(_ seq: [T], transform: ((T) -> U)) -> [U] { return seq.map { transform($0) } }
- //func Map<T, U>(_ seq: [T], transform: ((T) -> U)) -> [U] where T: Equatable, U: Equatable {
- // var result = [U]()
- // for f1 in seq { result.append(transform(f1)) }
- //
- // return result
- //}
- let mRes = Map([1,2,3]) { String($0) }
- mRes
- func Filter<T>(_ seq: [T], predicate: ((T) -> Bool)) -> [T] { return seq.filter { predicate($0) } }
- //func Filter<T>(_ seq: [T], predicate: ((T) -> Bool)) -> [T] {
- // var res: [T] = []
- // for f1 in seq {
- // if predicate(f1) {
- // res.append(f1)
- // }
- // }
- // return res
- //}
- let fRes = Filter([1,2,3]) { $0 % 2 != 0 }
- fRes
- let res = [1,2,3].reduce(0) { $0 + $1 }
- res
- // Reduce
- func Reduce<T, U>(_ seq: [T], initValue: U, reduce: ((U, T) -> U)) -> U {
- var result = initValue
- for f1 in seq {
- result = reduce(result, f1)
- }
- return result
- }
- let rRes = Reduce([1,2,3], initValue: 0) { $0 + $1 }
- rRes
- //////
- func onePlus(_ arr: [Int]) -> [String] {
- var input = [String]()
- for x in arr {
- input.append(String(x + 1))
- }
- return input
- }
- let oRes = onePlus([1,2,3])
- oRes
- func DumbMap(_ source: [Int], transform: ((Int) -> Int)) -> [Int] {
- var ret: [Int] = []
- for f1 in source {
- ret.append(transform(f1))
- }
- return ret
- }
- let dRes = DumbMap([1,2,3], transform: { $0 + 1 })
- dRes
- func SmartMap<T, U>(_ seq: [T], transform: ((T) -> U)) -> [U] { return seq.map { transform($0) } }
- let sRes = SmartMap([1,2,3]) { String($0 + 1) }
- sRes
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement