Difference between revisions of "W1349 Higher Order Functions"
From Coder Merlin
Line 411: | Line 411: | ||
let containsEye = {(ingredient:String) -> Bool in ingredient.contains("eye")} // | let containsEye = {(ingredient:String) -> Bool in ingredient.contains("eye")} // | ||
let bloodIngredients = ingredients.filter(containsBlood) | |||
let hairIngredients = ingredients.filter(containsHair) | |||
let eyeIngredients = ingredients.filter(containsEye) | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Which of the following produce identical results?<br/> | Which of the following produce identical results?<br/> | ||
'''A''' | '''A''' | ||
<syntaxhighlight lang="swift"> | <syntaxhighlight lang="swift"> | ||
let bloodIngredients = ingredients.filter {$0.contains("blood")} // | |||
let hairIngredients = ingredients.filter {$0.contains("hair")} // | |||
let eyeIngredients = ingredients.filter {$0.contains("eye")} // | |||
</syntaxhighlight> | </syntaxhighlight> | ||
'''B''' | '''B''' | ||
<syntaxhighlight lang="swift"> | <syntaxhighlight lang="swift"> | ||
let bloodIngredients = ingredients.map {$0.contains("blood")} // | |||
let hairIngredients = ingredients.map {$0.contains("hair")} // | |||
let eyeIngredients = ingredients.map {$0.contains("eye")} // | |||
</syntaxhighlight> | </syntaxhighlight> | ||
'''C''' | '''C''' | ||
<syntaxhighlight lang="swift"> | <syntaxhighlight lang="swift"> | ||
let bloodIngredients = ingredients.reduce {$0.contains("blood")} // | |||
let hairIngredients = ingredients.reduce {$0.contains("hair")} // | |||
let eyeIngredients = ingredients.reduce {$0.contains("eye")} // | |||
</syntaxhighlight> | </syntaxhighlight> | ||
'''D''' | '''D''' | ||
<syntaxhighlight lang="swift"> | <syntaxhighlight lang="swift"> | ||
let bloodIngredients = ingredients.filter {$1.contains("blood")} // | |||
let hairIngredients = ingredients.filter {$1.contains("hair")} // | |||
let eyeIngredients = ingredients.filter {$1.contains("eye")} // | |||
</syntaxhighlight> | </syntaxhighlight> | ||
|type="[]"} | |type="[]"} |
Revision as of 16:24, 24 March 2019
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Exercises[edit]
Professor Snape needs your help to organize ingredients for a wide variety of potions. You'll need to verify blocks of code to ensure that they're doing exactly what Professor Snape needs. Be careful! Any mistakes can be hazardous to his health. In some cases, more than one answer will be correct.