Question: I am trying to understand how can you pattern match in Erlang for single elements vs lists:

```
guarded(T) when T>5 ; T<3 -> 3+T;
guarded([X,Y]) when X>3,Y>3 ->{X+1,Y+1};
guarded([X,_|[T,_]]) when X rem 2==0, T rem 2 =/= 1-> [T,X];
guarded(_)->"something else".

guarded([1,2,3]).  -> goes into case 1 , how can i make sure it doesn't (and goes to last case)

```

> 
> \*\* exception error: an error occurred when evaluating an arithmetic expression
>  in function main:guarded/1
> 
> 
> 

Where would i need to place the first case , when i want to pattern match on single elements.I mean i want to have a case that works for single elements and a wild-card-pattern too (last expression).

Answer: 
You can add an [`is_list/1`](http://erlang.org/doc/man/erlang.html#is_list-1) check to your guards to check that `T` is not a list:

```
guarded(T) when not is_list(T) andalso (T>5 orelse T<3) -> 3+T;
guarded([X,Y]) when X>3, Y>3 ->{X+1,Y+1};
guarded([X,_|[T,_]]) when X rem 2==0, T rem 2 =/= 1-> [T,X];
guarded(_)->"something else".

```

Or you could use [`is_number/1`](http://erlang.org/doc/man/erlang.html#is_number-1) or [`is_integer/1`](http://erlang.org/doc/man/erlang.html#is_integer-1) to check that `T` is a number or an integer respectively:

```
guarded(T) when is_number(T) andalso (T>5 orelse T<3) -> 3+T;
guarded([X,Y]) when X>3, Y>3 ->{X+1,Y+1};
guarded([X,_|[T,_]]) when X rem 2==0, T rem 2 =/= 1-> [T,X];
guarded(_)->"something else".

```
> 
> I mean how does a method like `is_list` (mentioned above) implemented? 
> 
> 
> 

Using erlang, you can implement `is_list()` like this:

```
-module(my).
-compile([export_all]).

islist([]) ->     % empty list
    true;
islist([_|_]) ->  % non-empty list
    true;
islist(_) ->      % anything else
    false.

```

When you call a function, erlang starts with the first function clause in the definition and tries to match the arguments specified in the function call to the parameters in the function definition. If there's no match, erlang then tries the next function clause. When a match is found, the corresponding function body executes. If none of the function clauses match, then you get a `function_clause` error.

In the shell:

```
~/erlang_programs$ erl
Erlang/OTP 17 [erts-6.4] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V6.4  (abort with ^G)

1> c(my).
{ok,my}

2> my:islist(3).
false

3> my:islist({1, 2}).
false

4> my:islist([1, 2]).
true

5> my:islist([]).
true

6> my:islist("abc"). 
true

```

In line 6, you should be aware that `"abc"` is shorthand for the list of integers `[97, 98, 99]`. In erlang, a double quoted string is shorthand for a list that contains the integer codepoints of the characters in the double quoted string.