Software Studio: Functionals
Software Studio: Functionals
Software Studio: Functionals
studio
functionals
Daniel Jackson
functionals
since functions are first class
can pass functions as arguments
functions that take functions as args
are called functionals
can use functionals
to capture common idioms
examples
generators: a nice way to iterate over structures
list functionals: map, fold (reduce), filter
arrays: a refresher
Javascript operations
push/pop (back)
unshift/shift (front)
splicing
concatenation
autofilling
if set at index beyond length
elements in between set to undefined
> a = [3,5,7]
[3, 5, 7]
> a.push(9)
> a
[3, 5, 7, 9]
> a.unshift(1)
> a
[1, 3, 5, 7, 9]
> a.pop()
> a
[1, 3, 5, 7]
> a.shift()
> a
[3, 5, 7]
> a.splice(1,1,6)
[5]
> a
[3, 6, 7]
> a[4] = 8
> a
[3, 6, 7, undefined, 8]
>> s = 0;
...
6=> nil
...
Ruby
...
print e
Python
> sum([1,2,3])
6
var result = 0;
result += e;
});
return result;
}
4
map
result.push(f(e));
});
return result;
type
map: list[A] x (AB) list[B]
> twice = function (x) {return x * 2;}
> a = [1,2,3]
[1, 2, 3]
[2, 4, 6]
});
return result;
type
fold: list[A] x (A x BB) x B B
> times = function (x, y) {return x * y;}
> a = [1,2,3]
[1, 2, 3]
filter
if (p(e)) result.push(e);
});
return result;
type
filter: list[A] x (ABool) list[A]
> a = [1, 3, 5]
[1, 3, 5]
[1, 3]
> contains([1,2], 1)
false
in JQuery
each (collection, callback(index, value))
when callback returns false, iteration stops
in ECMAScript 5
array.forEach (callback(index,value,array))
MIT OpenCourseWare
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.