Skip to content
Snippets Groups Projects
Commit bd334772 authored by joel.vonderwe's avatar joel.vonderwe
Browse files

Added tp4 lambda

parent 8e982b9b
Branches
No related tags found
No related merge requests found
...@@ -98,7 +98,7 @@ object Serie3 { ...@@ -98,7 +98,7 @@ object Serie3 {
final def even[A]( as: List[A] ): Boolean = { final def even[A]( as: List[A] ): Boolean = {
as match { as match {
case Nil => true case Nil => true
case _ :: _ :: rest => evenRec(rest) case _ :: _ :: rest => even(rest)
case _ :: Nil => false case _ :: Nil => false
} }
} }
......
package ch.hepia.tpscala
/*
* Implémenter les fonctions suivantes en suivant les commentaires.
*/
object Predicates {
type P[A] = A=>Boolean
/*
* La méthode 'not' retourne un nouveau prédicat dont le résultat
* est toujours la négation du résultat de l'argument.
*/
def not[A]( p: (A)=>Boolean ): (A)=>Boolean = { (a:A) =>
!p(a)
}
/*
* La méthode 'and' retourne un nouveau prédicat dont le résultat
* est toujours la conjonction des résultats des deux arguments.
*/
def and[A]( p1: (A)=>Boolean, p2: (A)=>Boolean ): (A)=>Boolean = { (a:A) =>
p1(a) && p2(a)
}
/*
* La fonction 'or' retourne un nouveau prédicat dont le résultat
* est toujours la disjonction des résultats des deux arguments.
*/
def or[A]( p1: (A)=>Boolean, p2: (A)=>Boolean ): (A)=>Boolean = { (a:A) =>
p1(a) || p2(a)
}
/*
* La fonction 'exists' retourne un nouveau prédicat dont le
* résultat est vrai si au moins un des prédicat de l'argument est
* vrai.
*/
def exists[A]( ps: List[(A)=>Boolean] ): (A)=>Boolean = { (a:A) =>
ps match {
case p :: Nil => p(a)
case p :: _ if p(a) => true
case _ :: rest => exists(rest)(a)
}
}
/*
* La fonction 'forall' retourne un nouveau prédicat dont le
* résultat est vrai si et seulement si tous les prédicats de
* l'argument sont vrais.
*/
def forall[A]( ps: List[(A)=>Boolean] ): (A)=>Boolean = { (a:A) =>
ps match {
case p :: Nil => p(a)
case p :: _ if !p(a) => false
case _ :: rest => forall(rest)(a)
}
}
}
package ch.hepia.tpscala
import org.scalatest.funsuite.AnyFunSuite
import Predicates._
class PredicatesSuite4 extends AnyFunSuite {
val big = (_:Int) >= 100
val even = (_:Int) % 2 == 0
val small = not[Int]( big )
val bae = and[Int]( big, even )
val boe = or[Int]( big, even )
test("Predicate Evaluation") {
assert( big(200) )
assert( ! big(19) )
assert( even(200) )
assert( ! even(201) )
}
test("Predicate negation") {
assert( small(19) )
assert( !small( 200 ) )
}
test("Predicate AND") {
assert( bae( 200 ) )
assert( !bae( 201 ) )
}
test("Predicate OR") {
assert( boe( 201 ) )
assert( !boe( 19 ) )
}
val mul3 = (_:Int ) % 3 == 0
val ps = List( big, even, mul3 )
test("Predicates FORALL") {
assert( forall[Int]( ps )( 402 ) )
assert( ! forall[Int]( ps )( 200 ) )
}
test("Predicates EXISTS") {
assert( exists[Int]( ps )( 18 ) )
assert( ! exists[Int]( ps )( 1 ) )
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment