5 ms·
fact(match) = 0 or 1 -> 1 n -> n * fact(n - 1) why not simply fact(0 or 1) -> 1 fact(n) -> n * fact(n - 1)
by fenollp 11y ago
fact(match) =
0 or 1 -> 1
n -> n * fact(n - 1)
why not simply
fact(0 or 1) -> 1
fact(n) -> n * fact(n - 1)
- istvan__ 11y agoI think the first one is a single function that has pattern matching for the parameter while the second one is defining the function twice and relying on the language to call the right one based on the parameter. I think in Erlang the function identification is the name and the arity and this is as close I know of what you would like to have.
- TheDong 11y agoIn haskell you can write exactly the following: fact 0 = 0 fact 1 = 1 fact n = n * fact (n-1) It works as you would expect and really they aren't that dissimilar.
- FreeFull 11y agoSmall correction, fact 0 = 1
- arh68 11y agoErlang does it very much like GP's suggestion with the one downside of being 'noisy' with its punctuation (some might say 'clearer'): factorial(0) -> 1; factorial(N) -> N * factorial(N-1). factorial(Foo, 0) -> .. ; factorial(Foo, Bar) -> .. . Semicolons separate partial definitions for a single function of a single arity, and periods end those definitions. Removing the punctuation might make parsing a bit more difficult (will there be more partial definitions?), so it's understandable to not offer it.
- mikkom 11y agoErlang has both methods, pattern matching in function definition and case-clause pattern matching. (some random link http://stackoverflow.com/questions/1050913/erlang-style-case-vs-function-pattern-matching http://stackoverflow.com/questions/1050913/erlang-style-case...)
- akst 11y agoI'd imagine you could compile them both down to the same thing, as there has to be a conditional at some point to determine what code to run (unless there was some kind of dynamic dispatch), I think it's just a matter of preference
- deleted 11y ago[deleted]