@@ -18,30 +18,30 @@ import poly.{~>}
*/
object PolyExercises extends FlatSpec with Matchers with org.scalaexercises.definitions.Section {
object choose extends (Set ~ > Option ) {
def apply [T ](s : Set [T ]) = s.headOption
object choose extends (Seq ~ > Option ) {
def apply [T ](s : Seq [T ]) = s.headOption
}
/** `choose` is a function from Sets to Options with no type specific cases
/** `choose` is a function from Seqs to Options with no type specific cases
* {{{
* object choose extends (Set ~> Option) {
* def apply[T](s : Set [T]) = s.headOption
* object choose extends (Seq ~> Option) {
* def apply[T](s : Seq [T]) = s.headOption
* }
* }}}
*/
def exerciseChoose (res0 : Option [Int ], res1 : Option [Char ]) = {
import shapeless .poly ._
// choose is a function from Sets to Options with no type specific cases
// choose is a function from Seqs to Options with no type specific cases
choose(Set (1 , 2 , 3 )) should be(res0)
choose(Set ('a' , 'b' , 'c' )) should be(res1)
choose(Seq (1 , 2 , 3 )) should be(res0)
choose(Seq ('a' , 'b' , 'c' )) should be(res1)
}
/** Being polymorphic, they may be passed as arguments to functions or methods and then applied to values of different types
* within those functions
*/
def exercisePairApply (res0 : Option [Int ], res1 : Option [Char ]) = {
def pairApply (f : Set ~ > Option ) = (f(Set (1 , 2 , 3 )), f(Set ('a' , 'b' , 'c' )))
def pairApply (f : Seq ~ > Option ) = (f(Seq (1 , 2 , 3 )), f(Seq ('a' , 'b' , 'c' )))
pairApply(choose) should be(res0, res1)
}
@@ -51,7 +51,7 @@ object PolyExercises extends FlatSpec with Matchers with org.scalaexercises.defi
* mapped across an ordinary Scala List
*/
def exerciseMonomorphicChoose (res0 : Option [Int ], res1 : Option [Int ]) =
(List (Set (1 , 3 , 5 ), Set (2 , 4 , 6 )) map choose) should be(List (res0, res1))
(List (Seq (1 , 3 , 5 ), Seq (2 , 4 , 6 )) map choose) should be(List (res0, res1))
/** However, they are [[http://www.chuusai.com/2012/05/10/shapeless-polymorphic-function-values-2/ more general than natural transformations ]] and are able to capture type-specific cases
* which, as we'll see below, makes them ideal for generic programming,