我正在学习Haskell并从教程网站编写了两个程序
maximumnowhere :: (Ord a) => [a] -> a
maximumnowhere [] = error "empty"
maximumnowhere [x] = x
maximumnowhere (x:xs) = if x > maximumnowhere xs then x else maximumnowhere xs
Run Code Online (Sandbox Code Playgroud)
和
maximumwhere :: (Ord a) => [a] -> a
maximumwhere [] = error "empty"
maximumwhere [x] = x
maximumwhere (x:xs) = if x > maximum' then x else maximum' where maximum' = maximumwhere xs
Run Code Online (Sandbox Code Playgroud)
我认为这两个程序是完全等价的,因为我认为,where绑定只会将变量替换为其内容.但是当我在ghci中运行时,第一个比后者慢,特别是对于长度超过25的数组.可能,where绑定会产生巨大的性能差异,但我不知道为什么.有谁可以帮我解释一下?
我是Java新手,只是用BigInteger编写程序代码.
public static void main(String[] args) {
BigInteger n = new BigInteger("5");
BigInteger i = new BigInteger("2");
while (lesserOrEqual(i,n) {
System.out.println("n.mod(i) = "+n.mod(i));
if (n.mod(i) == ZERO) {
n = n.divide(i);
}
else {
i.add(ONE);
}
System.out.println("n = "+n);
System.out.println("i = "+i);
}
public static boolean lesserOrEqual(BigInteger m, BigInteger n) `{
if (m.compareTo(n) == -1 || m.compareTo(n) == 0)
return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
ZERO和ONE分别由BigInteger 0,1类型定义.
我希望"i = 2"除以"n = 5",如果"n mod i == 0",则"i ++",直到"n"小于或等于"i".
我认为输出必须是
n.mod(i) = 1 …
Run Code Online (Sandbox Code Playgroud)