在zsh中定义数学函数?

3

这几乎肯定是一个重复的问题,但我找不到我要找的帖子。

我主要在工作中使用bash,但我偶尔会将zsh用作浮点计算器。虽然zsh/mathfunc库对于sqrtsin等都很好,但我希望在zsh中定义其他数学函数,例如pow,使它们按以下方式运行:

zsh% print $((pow(4.0, 4.0) + 1.0))
257.0

(是的,我知道内置的**操作符,这只是一个例子)
我得到的最接近的答案是使用类似于print $(($(pow 4.0 4.0) + 1.0))的函数,正如laviande22所演示的那样,但这会让人头痛。
请注意:我不是在寻找一个答案,当命令在裸 zsh 中键入时,它会给出答案,例如zsh% pow 4 4。我正在寻找一个可以在给定形式中的数学子系统中使用的函数,即zsh% print $((pow(4.0, 4.0)))
2个回答

3

functions -M mathfn 可以帮助我们。它定义了一个数学函数,因此我们可以使用类似算术函数调用表达式的形式来调用函数,例如 mathfn(arg,...)

my-powi () {
  res=1
  for ((i=0; i<$2; i++))
    ((res = res * $1))
  return res
}

functions -M pow 2 2 my-powi

echo $((pow(4, 4) + 1))
# >> 257

这里是zsh文档:

functions -M [-s] mathfn [ min [ max [ shellfn ] ] ]
...
functions -M mathfn defines mathfn as the name of a mathematical function recognised in all forms of arithmetical expressions; see Arithmetic Evaluation. By default mathfn may take any number of comma-separated arguments. If min is given, it must have exactly min args; if min and max are both given, it must have at least min and at most max args. max may be -1 to indicate that there is no upper limit.
...
For example, the following prints the cube of 3:

zmath_cube() { (( $1 * $1 * $1 )) }
functions -M cube 1 1 zmath_cube
print $(( cube(3) ))

--- zshbuiltin(1), functions, Shell Bultin Commands


1
这个可以工作,但重新定义函数有点笨拙,尽管这不是一个大问题,因为数学函数往往总是做同样的事情。谢谢。 - guninvalid

0
你可以在你的.zshrc文件中定义函数,或者导入包含函数定义的其他shell脚本到你的rcfile中。
例如,你可以在.zshrc中编写一个函数,像这样:
# In ~/.zshrc

function pow() {
    res=1
    for i in {1..$2};
        res=$((res * $1))
    echo $res
}

然后你可以发出像pow 2 4这样的命令,它将回显16。当你启动shell时,Zsh会加载rcfile中的任何内容,因此你不必每次都定义需要的所有函数。如果你不熟悉zsh或bash的语法,你可能想要谷歌一下。或者也许你可以从这个bash cheat sheet开始。

你还可以创建一个新的脚本文件并将其包含在rcfile中。

# In ~/.zshrc

if [ -f ~/.custom_functions ]; then  # The file name is arbitrary.
    . ~/.custom_functions
fi

我看到了这个答案,它有所帮助,但并不完全符合我的需求。我已经编辑了我的问题,希望更清晰明了。 - guninvalid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接