maoyi
maoyi

Reputation: 453

The difference between comma and | in erlang

I am trying to create a function that returns the last element of a list. However something is kinda strange here.

last([X,[]]) -> X;
last([_X|Xs]) -> last(Xs).

This returns a no-matching clause error. But if I change the first line into last([X|[]]) -> X; it will work correctly. I think both of lines mean the same thing but it clearly has different results. Am I missing something important here?

Upvotes: 2

Views: 121

Answers (1)

Steve Vinoski
Steve Vinoski

Reputation: 20004

A comma separates list elements while a | separates the head of a list from its tail. [X,[]] is a list of two elements, X and the empty list []. But [X|[]] is a list of one element, X, with an empty tail.

BTW you might just use lists:last/1 instead of writing your own function.

Upvotes: 4

Related Questions