Functional Programming: Difference between revisions

From Federal Burro of Information
Jump to navigationJump to search
(Created page with "notes from the field. In general, new_collection = collection.map(function) is a short-cut for: new_collection[] for (element in collection) new_collection[] += funct...")
 
No edit summary
 
Line 32: Line 32:


that
that
:Example
you want to remove all the gcp images not in use, get all the current live instance, find their template, find the image in the template and "subtract" those from the list of all images.
<pre>
source_images = instance
  .map(i => i.get_template)
  .map(i => i.get_source_image)
to_delete = gci.get_all()
  .filter(i => !source_images[i])
  .filter(i => i.age > 1m)
for i in to_delete:
  i.delete() 
</pre>

Latest revision as of 19:00, 17 November 2020

notes from the field.

In general,

new_collection = collection.map(function)

is a short-cut for:

new_collection[]
for (element in collection)
 new_collection[] += function(element)

And:

new_collection = collection.filter(function)

is a short-cut for:

new_collection[]
for (element in collection):
  if function(element):
    new_collection[] += function(element)

this

doubled = [1, 2, 3, 4, 5].map(x => x * 2)

is equivalent to:

doubled[]
for (x in [1, 2, 3, 4, 5]):
  doubled[] += x * 2

that


Example


you want to remove all the gcp images not in use, get all the current live instance, find their template, find the image in the template and "subtract" those from the list of all images.



source_images = instance
  .map(i => i.get_template)
  .map(i => i.get_source_image)

to_delete = gci.get_all()
  .filter(i => !source_images[i])
  .filter(i => i.age > 1m)

for i in to_delete:
  i.delete()