Difference between revisions of "W1349 Higher Order Functions"
From Coder Merlin
Line 199: | Line 199: | ||
+ C | + C | ||
+ D | + D | ||
{ | |||
Professor Snape needs to preserve the order of the following ingredients but include only those that begin with the letter "F". He knows that one way of doing this is as follows: | |||
<syntaxhighlight lang="swift"> | |||
let ingredients = ["bat spleen", "beetle eye", "dragon blood", "eel eye", "foxglove", "frog brain", "griffin claw"] | |||
let startsWithF = {(string:String) -> Bool in string.starts(with:"f")} // | |||
let fIngredients = ingredients.filter(startsWithF) | |||
</syntaxhighlight> | |||
Which of the following produce identical results?<br/> | |||
'''A''' | |||
<syntaxhighlight lang="swift"> | |||
var fIngredients = [String]() | |||
for i in 0 ..< ingredients.count { | |||
if ingredients[i].starts(with:"f") { | |||
fIngredients.append(ingredients[i]) | |||
} // | |||
} // | |||
</syntaxhighlight> | |||
'''B''' | |||
<syntaxhighlight lang="swift"> | |||
var fIngredients = [String]() | |||
for i in stride(from:0, to:ingredients.count, by: 1) { | |||
if ingredients[i].starts(with:"f") { | |||
fIngredients.append(ingredients[i]) | |||
} // | |||
} // | |||
</syntaxhighlight> | |||
'''C''' | |||
<syntaxhighlight lang="swift"> | |||
var fIngredients = [String]() | |||
for i in stride(from:0, through:ingredients.count, by: 1) { | |||
if ingredients[i].starts(with:"f") { | |||
fIngredients.append(ingredients[i]) | |||
} // | |||
} // | |||
</syntaxhighlight> | |||
'''D''' | |||
<syntaxhighlight lang="swift"> | |||
var fIngredients = [String]() | |||
for i in stride(from:ingredients.count-1, through:0, by: -1) { | |||
if ingredients[i].starts(with:"f") { | |||
fIngredients.append(ingredients[i]) | |||
} // | |||
} // | |||
</syntaxhighlight> | |||
|type="[]"} | |||
+ A | |||
+ B | |||
- C | |||
- D | |||
</quiz> | </quiz> |
Revision as of 13:19, 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.