Last active
December 13, 2017 17:18
-
-
Save Leonidas-from-XIV/d36699b7ea79cc427348d5ec27af6a6c to your computer and use it in GitHub Desktop.
Why if needs to be an expression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 *) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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? |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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