Specific treatment for the first and last element of sequence in a function?

174 Views Asked by At

Let $A = \langle a_1,\dots,a_n \rangle$ be a sequence. I have a function that given any element $a_k$ it will return the values of $a_{k-1}+a_k+a_{k+1}$ with the exception of the first and last element that is going to return $a_k + a_{k+1}$ for the first element and $a_k + a_{k-1}$ for the last one:

$ f(k) = \left\{ \begin{array}{l l} a_k + a_{k+1} & \quad \text{if $k=1$}\\ a_k + a_{k-1} & \quad \text{if $k=n$}\\ a_{k-1}+a_k+a_{k+1} & \quad \text{otherwise} \end{array} \right.$

Is there any better (more compact) way of writing this function?

1

There are 1 best solutions below

2
On

I'd write this as

For $1\le k\le n$ let $f(k)=a_{k-1}+a_k+a_{k+1}$, with the convention that $a_0=a_{n+1}=0$.

Note that this formulation even covers the case $n=1$ correctly (which the cases-statement does not).