Last active
December 13, 2015 18:29
-
-
Save sam/4955723 to your computer and use it in GitHub Desktop.
Variations implementing a recursive filter() function in Scala. One using for-comprehensions, one using iterators. Another using a method instead.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Normally you define the type of a value like so: | |
// | |
// val name:String = "bob" | |
// | |
// The pattern here is varname:Type = Value | |
// If you need to specify the Type for an anonymous function, | |
// it'll follow the pattern: | |
// | |
// (ParamemterType1, ParameterType2) => ReturnType | |
// | |
// If you need to assign an anonymous function to a val, | |
// and specify it's type (which is necessary with a recursive function), | |
// then you'll be substituting the Type bit in the first pattern with | |
// the anonymous function type signature. So something like this: | |
// | |
// val name:(Type1) => ReturnType = Value | |
// | |
// Value in this case needs to be a function with the type signature | |
// specified. For example: | |
// | |
// val lengthOfString:(String) => Int = (s:String) => s.length | |
// | |
// TADA! | |
// | |
// Extra Credit: | |
// | |
// We could also write the above function like so: | |
// | |
// val lengthOfString = (_:String).length | |
// | |
// See if you can explain how/why that works! | |
val filter:(Int) => Unit = (candidateId:Int) => for { | |
channel <- channels if !invalid(channel.id) && channel.parentId.fold(false)(_ == candidateId) | |
} { | |
invalid += channel.id | |
filter(channel.id) | |
} | |
val filter2:(Int) => Unit = (candidateId:Int) => channels.foreach { channel => | |
if(!invalid(channel.id) && channel.parentId.fold(false)(_ == candidateId)) { | |
invalid += channel.id | |
filter2(channel.id) | |
} | |
} | |
def filter3(candidateId:Int):Unit = for { | |
channel <- channels if !invalid(channel.id) && channel.parentId.fold(false)(_ == candidateId) | |
} { | |
invalid += channel.id | |
filter3(channel.id) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI, the original Ruby version of the above filter method was:
In hind-sight, an
#each
would've been sufficient, making it more equivalent with the above Scala, and iterating fewer times.