From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 24973 invoked by alias); 7 Feb 2016 00:28:54 -0000 Mailing-List: contact zsh-users-help@zsh.org; run by ezmlm Precedence: bulk X-No-Archive: yes List-Id: Zsh Users List List-Post: List-Help: X-Seq: 21248 Received: (qmail 25581 invoked from network); 7 Feb 2016 00:28:54 -0000 X-Spam-Checker-Version: SpamAssassin 3.4.1 (2015-04-28) on f.primenet.com.au X-Spam-Level: X-Spam-Status: No, score=-1.9 required=5.0 tests=BAYES_00 autolearn=ham autolearn_force=no version=3.4.1 Date: Sun, 07 Feb 2016 00:22:12 +0000 From: Daniel Shahaf To: Zsh Users Subject: min() max() math functions (was: Re: Feature request (@M):# with context matches) Message-ID: <20160207002212.GC24068@tarsus.local2> References: <160130085456.ZM9730__49922.0612728552$1454172936$gmane$org@torch.brasslantern.com> MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Disposition: inline Content-Transfer-Encoding: 8bit In-Reply-To: <160130085456.ZM9730__49922.0612728552$1454172936$gmane$org@torch.brasslantern.com> User-Agent: Mutt/1.5.23 (2014-03-12) Bart Schaefer wrote on Sat, Jan 30, 2016 at 08:54:56 -0800: > So you want something like > > while (( ( hit = $list[(i)*$search_pattern*] ) < $#list )) > do > print -r -- $list[hit-3,hit+3] > shift $hit list > done > > with some appropriate checking that (hit-3) doesn't become negative and > wrap around to the other end of the array, [...] I've wished a number of times for a built-in max() math function, which would allow: $list[max(hit-3, 0), hit+3] There are a number of places in the distribution that could use this: % git grep '[(][(].*[?].*[:]' Completion/Unix/Command/_git: (( n = $#file > $#prefix ? $#file : $#prefix )) Completion/Zsh/Type/_ps1234: (( cols = cols > 255 ? 255 : cols )) Functions/Misc/zargs: shift $((end > ARGC ? ARGC : end)) Functions/Zle/modify-current-argument: (( CURSOR = wordoff + (poschar > repmax ? repmax : poschar) - 1 )) I also needed this a number of times in my zshrc, too, such as for . MANWIDTH=$(( min(COLUMNS, 80) )) I imagine that function would be variadic and take parameters of any numeric type... Something along these lines: _mathfunc_min _mathfunc_max() { local result=$1 ; shift while (( $# )) ; do case $0 in (max) (( $1 > result )) && result=$1;; (min) (( $1 < result )) && result=$1;; esac shift done (( result )) # return } functions -M max 1 -1 _mathfunc_max # at least one argument functions -M min 1 -1 _mathfunc_min # at least one argument And while at it: _mathfunc_sum() { local sum while (( $# )) ; do (( sum += $1 )) shift done (( sum )) } functions -M sum 0 -1 _mathfunc_sum Cheers, Daniel