added assignment 5 ex 2
This commit is contained in:
		
							
								
								
									
										36
									
								
								src/Assignment5/Folds.sc
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										36
									
								
								src/Assignment5/Folds.sc
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,36 @@ | ||||
| def areTrue(booleans: List[Boolean]): Boolean = { | ||||
|   booleans.foldLeft(true)((acc, value) => acc && value) | ||||
| } | ||||
|  | ||||
| def lString(strings: List[String]): Int = { | ||||
|   strings.foldLeft(0)((len, str) => len + str.length) | ||||
| } | ||||
|  | ||||
| def longest(strings: List[String]): Int = { | ||||
|   strings.foldLeft(0)((maxLen, str) => if (str.length > maxLen) str.length else maxLen) | ||||
| } | ||||
|  | ||||
| def isPresent[T](list: List[T], target: T): Boolean = { | ||||
|   list.foldLeft(false)((res, value) => res || value == target) | ||||
| } | ||||
|  | ||||
| def flattenList(list: List[Any]): List[Any] = { | ||||
|   list.foldRight(List.empty[Any])((elem, acc) => { | ||||
|     elem match { | ||||
|       case l: List[Any] => flattenList(l).foldRight(acc)((e, l) => e::l) | ||||
|       case _ => elem::acc | ||||
|     } | ||||
|   }) | ||||
| } | ||||
|  | ||||
| assert(!areTrue(List(true, true, false))) | ||||
| assert(areTrue(List(true, true, true))) | ||||
|  | ||||
| assert(lString(List("Folding", "is", "fun")) == 12) | ||||
|  | ||||
| assert(longest(List("What", "is", "the", "longest?")) == 8) | ||||
|  | ||||
| assert(!isPresent(List(1, 2, 3, 4), 5)) | ||||
| assert(isPresent(List(1, 2, 3, 4), 3)) | ||||
|  | ||||
| assert(flattenList(List(List(1, 1), 2, List(3, List(5, 8)))) == List(1, 1, 2, 3, 5, 8)) | ||||
		Reference in New Issue
	
	Block a user