Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

min() max() math functions (was: Re: Feature request (@M):# with context matches)



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



Messages sorted by: Reverse Date, Date, Thread, Author