adding cycle checking and returning something when some branch terminates
adding scala solution