# [erlang-questions] View patterns

Ulf Wiger (TN/EAB) <>
Wed Jul 25 15:40:30 CEST 2007

```
ok wrote:
>
> One of the things which is about to be added to GHC
> is view patterns.
> The idea is that if E is an expression and P is a
> pattern, then
> 	(E -> P)
> is a pattern.  This pattern matches a value V if
> and only if P = (E)(V).
>
[...]
>
> People who dislike n+k patterns in Haskell can no longer hurt
> us much by taking them out.  With the aid of
>
> 	np(K, X) when integer(X), integer(K), X >= K ->
> 	    {X};
> 	np(_, _) ->
> 	    false.
>
> we can rewrite
>
> 	factorial(0) -> 1;
> 	factorial(N+1) -> (N+1)*factorial(N).
>
> as
>
> 	factorial(0) -> 1;
> 	factorial((np(1) -> {N})) -> (N+1)*factorial(N).

Interesting stuff.

I'm a bit unsure about the semantics of this
last one. I wrote a parse transform to allow for
experimentation with view patterns without revising
the Erlang grammar, and changed the above to:

factorial(0) -> 1;
factorial(_:_(np, [1], {N}) ->
(N+1)*factorial(N).

(Obviously not an improvement over your syntax)

which was transformed into:

np(K, X) when integer(X),
integer(K), X >= K ->
{X};
np(_, _) ->
false.

factorial(0) ->
1;
factorial(V73) ->
case np(1, V73) of
{N} ->
(N + 1) * factorial(N);
_ ->
erlang:error(function_clause)
end.

But something is obviously wrong, since this
will not terminate.