【发布时间】:2013-01-22 01:32:04
【问题描述】:
我想检查前一个if condition 的条件以确定下一个if condition 是否被执行。每个if condition 都可能返回一个值。
编辑:抱歉,我之前提供的示例看起来有点奇怪......:( 这是我的真实示例,我想为 goingToMove
简化if-then-else
goingToMove p routes points w h =
if canMove p points
-- the point can be moved in the map
then let r = routes ++ [p]
l = remainList p points
in move p r l w h
-- the point cannot be moved in the maps
else []
move p routes points w h =
if (length routes) == 2
then routes
else let one = goingToMove (tallRightCorner p) routes points w h in
if (null one)
then let two = goingToMove(tallRightBCorner p) routes points w h in
if (null two)
then let three = goingToMove (tallLeftBCorner p ) routes points w h in
if (null three)
then ....
...... -- until, let eight = ..
else three
else two
else one
编辑:不好的例子 当这个东西用java写的时候,我可能会使用一个可变的布尔标志,并返回一个可变的数据。
public String move (int number){
// base case
if (number == 0){
return "Finished the recursion";
}
// general case
else {
String result;
boolean isNull = false;
if ((result = move(3)) == null){
isNull = true;
}
else {
return result;
}
// continue to execute the if-conditions if the previous condition failed
if (isNull){
if((result = move(2)) == null){
isNull = true;
}
else {
return result;
}
}
if (isNull){
if((result = move(1)) == null){
isNull = true;
}
else {
return result;
}
}
return null;
}
}
但在 Haskell 中,没有可变数据,只有if-then-else 条件。 然后代码会是这样,我想简化一下,因为在我的实际工作中,有 8 个if-then-else 的级别看起来很糟糕而且很乱......
move 0 = "Finished the recursion"
move n =
let one = move 3 in
if null one
then let two = move 2 in
if null two
then let three = move 1 in
then null
else three
else two
else one
【问题讨论】:
-
您在 Java 代码中调用的
move是否与您定义的move相同?如果是这样,我看不出它对于非零输入如何不会无限循环。move(3)打电话给move(3)打电话给move(3)... -
您提供的 haskell 代码也有错误的类型。您在 java 代码中的某个位置显式返回
null,这意味着haskell 代码应该是Int -> Maybe String,即使它不是无限循环。哦,您建议的 haskell 代码也有语法错误(缺少包含 if 的行?),因此很难弄清楚您在做什么。 -
我提供了一个真实的例子:(对不起
-
你应该从使用更多的模式匹配和更少的条件开始。你还有一堆多余的
lets,你不需要括号if表达式的条件。
标签: haskell if-statement recursion functional-programming tail-recursion