Skip to content

Instantly share code, notes, and snippets.

@Leonidas-from-XIV
Last active December 13, 2017 17:18
Show Gist options
  • Save Leonidas-from-XIV/d36699b7ea79cc427348d5ec27af6a6c to your computer and use it in GitHub Desktop.
Save Leonidas-from-XIV/d36699b7ea79cc427348d5ec27af6a6c to your computer and use it in GitHub Desktop.
Why if needs to be an expression
let result = match is_correct some_value with
| true -> some_result_function 42
| false -> some_error_function 23
in
(* use result here, no mutation, generalizes to n cases easily *)
result = None
if is_correct(some_value):
result = some_result_function(42)
else:
result = some_error_function(23)
# use result here
# but now you have mutation
# also, what happens if you forget to set result in one of the branches?
result = some_result_function(42) if is_correct(some_value) else some_error_function(23)
# use result here
# but now it is hard to read, the condition is in the middle
# and if you have more than simple code in your branches the code will get even worse
# also, it only works for if/else, but not for if/elseif/elseif/elseif/else
def _inner(condition):
if condition:
return some_result_function(42)
else:
return some_error_function(23)
result = _inner(is_correct(some_value))
# use result here
# no mutation
# but now every time you want to use if/then/else you need to write it as a function with some meaningless name
# and then call it
# what happens if you forget to return in one of the branches?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment