Advertisement
wavec022

recursion

Aug 19th, 2020 (edited)
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.50 KB | None | 0 0
  1. def max(list: List[Int]): Int = {
  2. if(list.isEmpty) Int.MinValue
  3. else list.head max max(list.tail)
  4. }
  5.  
  6. def max2(list: List[Int]): Int = {
  7. if(list.tail.isEmpty) list.head
  8. else {
  9. val newMax = max(list.tail)
  10. if(list.head > newMax) list.head
  11. else newMax
  12. }
  13. }
  14.  
  15. =====
  16.  
  17. Or we can use an accumulating parameter? and something involving a helper function
  18.  
  19. def maxH(maxSoFar: Int, list: List[Int]): Int = {
  20. if (list.isEmpty) maxSoFar
  21. else maxH(maxSoFar max list.head, list.tail)
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement