In python or coffeescript, why list.append not return the list itself ? recursion can be a lot simpler if so
consider the following code if insert() return the list itself.
def sieve(l):
if not len(l):
return []
return sieve(filter(lambda x: x%l[0] != 0, l)).insert(0, l[0])
For now, we have to rely on a helper function to return the list after insertion.
def cons(a, l):
l.insert(0, a)
return l
def sieve(l):
if not len(l):
return []
return cons(l[0], sieve(filter(lambda x:x%l[0] != 0, l)))
The point of mutable/immutable object is totally valid.
However, for lists that are mutable, IMHO, append() API could take one more step to return the list itself, rather than not returning anything. Java StringBuilder i开发者_运维百科s a good example. I can do chained append on stringbuilder object recursively....Just wish we could have this here also.
In Python, it is a big deal to get beginners to learn which objects are “immutable” and cannot be changed, and which are “mutable” and can be altered — in the latter case, every reference to the object sees the same change. This really seems to confuse newcomers. “I innocently called this function I wrote, and suddenly my copy of the list is changed too!”
So Python has a convention: immutable objects, when you ask them to make an adjustment, return the newly-created object that is the answer — so:
a = 'my string'
b = a.replace('y', 'e')
makes b
get an entirely new string while a
keeps its original value. Obviously such methods must return a value, since you cannot see the change, ever, by inspecting the original, immutable object itself.
But when you ask a mutable object to change itself, it does not return itself, because it does not need to — you can see the change just by looking at the original object again! This is a critical semantic signal in Python: if a method like append()
does not return a new object, then you can see the change just by looking at the old object, and so can everyone else with a reference to the old object.
Since you asked about CoffeeScript...
The push
method modifies the array in-place. Rather than returning the newly modified array, it returns the value you just added. That's unintuitive, granted, but it can be useful. For instance, you can write things like
getNewValue -> cache.push fetchValue()
which, in one line, fetches a value, adds it to the cache
, and returns it from getNewValue
.
The concat
method, on the other hand, doesn't modify the original array, instead returning the modified copy. It's supposed to be used for concatenating two arrays, but non-array values will be coerced, so you can use it as a push
substitute if you want:
arr = [1, 2, 3]
arr = arr.concat 4
console.log arr # [1, 2, 3, 4]
Full documentation on JavaScript's array methods is available on MDN.
Why not just create a reference? I think that will make the code more readable as well.
精彩评论