#!/usr/bin/python from go import * # Problem: process just the numbers in the following.... x = ["a", [], 1, 2, [ "b", 3, 4 ] ] def nump(x): return isinstance(x, (int, long, float, complex)) # Solutions # 1111111111 # Solution #1: pass around a lambda body def rwalk(thing,f,tmp): if isinstance(thing,list): for any in thing: tmp = rwalk(any,f,tmp) else: tmp = f(tmp,thing) return tmp def rSum(x): def worker(old,new): return old+new if nump(new) else old return rwalk(x,worker,0) @go def _rSum(): print rSum(x) def rKeep(x): def worker(lst,new): if nump(new): lst += [new] return lst return rwalk(x,worker,[]) @go def _rKeep(): print rKeep(x) # 222222222 # Solution #2: iterators def rItems(thing): if isinstance(thing,list): for any in thing: for one in rItems(any): yield one else: yield thing @go def _recursiveAdd(): n = 0 for i in rItems(x): if nump(i): n += i print n @go def _recursiveAccum(): out = [] for i in rItems(x): if nump(i): out += [i] print out