前の状態をチェックして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