scala - How to convert recursion to fold -


according erik meijer, functional programmers, know instead of recursion, should use fold. how convert following use fold? can see 1 way return, return should avoided in fp. thanks!

def tryold(string: string, original: exception, zomoldlist: list[string => double]): double = {   zomoldlist match {     case nil =>       throw original     case head :: tail =>       try {         head(string)       } catch {         case ex: exception =>           tryold(string, original, tail)       }   } } 

you can implement foldright taking advantage of functions being values:

import util.control.nonfatal def tryold(string: string, original: exception, zomoldlist: list[string ⇒ double]): double = {   val unhandled: string ⇒ double = _ ⇒ throw original   zomoldlist.foldright(unhandled) { (f, z) ⇒     x ⇒ try { f(x) } catch { case nonfatal(_) ⇒ z(x) }   }(string) } 

note use nonfatal here avoid catching exceptions shouldn't catching. can write in more elegant way not using exceptions directly.


Comments

Popular posts from this blog

android - Automated my builds -

how to proxy from https to http with lighttpd -

python - Flask migration error -