Pandemonium
Pandemonium

Reputation: 8390

Use of Multiple Function Clause Heads

I'm learning Erlang and curious about this pattern of using multiple function clause heads. Here is an example:

sum_left(L, 0) ->
    L;
sum_left(L, N) -> 
    [ First, Second | Rest ] = L,
    L_ = [First + Second | Rest],
    sum_left(L_, N - 1).

This is more commonly seen than the use of case ... of within a single function declaration, as seen in languages like Haskell and Ocaml:

sum_left(L, N) ->
    case N of
        0 -> 
            L;
        _ -> 
            [ First, Second | Rest ] = L,
            L_ = [First + Second | Rest],
            sum_left(L_, N - 1)
    end.

Aside from cosmetic reasons such as readability and conciseness of a function body, what might have been a motivation for the first convention over the second one?

EDIT: As pointed out by the answer, it is possible to use function clauses in Haskell.

Upvotes: 1

Views: 116

Answers (1)

Joonazan
Joonazan

Reputation: 1416

You can use this in Haskell as well, and at least I prefer it over using case, because it results in less indentation and you do not need to wrap arguments in a tuple.

For example:

interleave (x:xs) (y:ys) = x : y : interleave xs ys
interleave [] ys = ys
interleave xs [] = xs

Upvotes: 1

Related Questions