function - Swift writing map, length, filter as reduce -
as exercise, i'm trying write map, length , filter reduce function.
func map<t>(array: [t], f: (t->t)) -> [t] { return array.reduce([]) { (var seed, value) in seed.append(f(value)) return seed } } func length<t>(array: [t]) -> int { return array.reduce(0){ (x,_) in x + 1 } } func filter<t>(array: [t], predicate: (t->bool)) -> [t]{ return array.reduce([]){ (var seed, value) in if predicate(value){ seed.append(value) } return seed } } is elegant syntax can use rewrite functions reduce? 2nd question: map takes function f:(t->t) type says can return of type t, if function write transforms type t bool, or , int... how accomplish this? seems map doesn't exist
for mapping transforms type t (possibly different) type s use two type placeholders:
func map<t, s>(array: [t], f: (t->s)) -> [s] { return array.reduce([]) { (var seed, value) in seed.append(f(value)) return seed } } example:
let x = map([1, 2, 3], f: { string($0) }) print(x) // ["1", "2", "3"] whether "is elegant syntax" matter of personal opinion. if replace append() method array concatenation + seed parameters needs not variable:
func map<t, s>(array: [t], f: (t->s)) -> [s] { return array.reduce([]) { (seed, value) in seed + [f(value)] } } which can written shorthand parameter names as
func map<t, s>(array: [t], f: (t->s)) -> [s] { return array.reduce([]) { $0 + [ f($1) ] } } similarly:
func filter<t>(array: [t], predicate: (t->bool)) -> [t]{ return array.reduce([]) { predicate($1) ? $0 + [ $1 ] : $0 } } just note implementation of map() , filter() using reduce() (instead of loop) quite ineffective because new array created in each reduction step. see example
for analysis. exercise (as said) fine, don't use in production).
Comments
Post a Comment