added assignment 4 ex 4
This commit is contained in:
		
							
								
								
									
										24
									
								
								src/Assignment4/Ex4_Predicates.sc
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										24
									
								
								src/Assignment4/Ex4_Predicates.sc
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,24 @@ | ||||
| import scala.annotation.tailrec | ||||
|  | ||||
| @tailrec | ||||
| def any[T](p: T => Boolean)(l: List[T]): Boolean = { | ||||
|   if (l.isEmpty) false | ||||
|   else if (p(l.head)) true | ||||
|   else any(p)(l.tail) | ||||
| } | ||||
|  | ||||
| @tailrec | ||||
| def every[T](p: T => Boolean)(l: List[T]): Boolean = { | ||||
|   if (l.isEmpty) true | ||||
|   else if (!p(l.head)) false | ||||
|   else every(p)(l.tail) | ||||
| } | ||||
|  | ||||
| val a = List(1, 2, 3, 4, 5) | ||||
| assert(!any((x: Int) => x == 12)(a)) | ||||
| assert(any((x: Int) => x > 4)(a)) | ||||
|  | ||||
| val a = List(1, 2, 3, 4, 5) | ||||
| val b = List(2, 4, 6, 8, 10) | ||||
| assert(!every((x: Int) => (x % 2) == 0)(a)) | ||||
| assert(every((x: Int) => (x % 2) == 0)(b)) | ||||
		Reference in New Issue
	
	Block a user