1
\$\begingroup\$

How do I refactor this mess of if/else conditions so that it's more readable?


 ( Reverse_Path = [[]] -> Child = [c(New_Score,G1,Pos),P]
 ; otherwise -> Child = [c(New_Score,G1,Pos),P|Reverse_Path]
 ),
 ( memberchk(Child,NewAgenda) -> addChildren(Others,Reverse_Path,Current,NewAgenda,Target,Result)
 ; otherwise -> 
 ( NewAgenda=[] -> BrandNewAgenda = [Child|NewAgenda]
 ; otherwise -> 
 (New_Score =< FP -> BrandNewAgenda = [Child|NewAgenda];
 otherwise -> append(NewAgenda,[Child],BrandNewAgenda)
 )
 ),
 )).
Doi9t
3,3643 gold badges11 silver badges23 bronze badges
asked Apr 20, 2020 at 19:08
\$\endgroup\$
1
  • \$\begingroup\$ What is the purpose of the code, apart from being a mess? \$\endgroup\$ Commented Apr 21, 2020 at 5:00

1 Answer 1

2
\$\begingroup\$

Generally speaking, you can resolve if/else logic by using multiple clauses for the same predicate, as multiple clauses implicitely represent 'or' or 'case', e.g.:

foo([[]], Child) :-
 Child = [c(New_Score,G1,Pos),P].
foo(Reverse_Path, Child) :-
 Child = [c(New_Score,G1,Pos),P|Reverse_Path].
bar(Reverse_Path, Child, NewAgenda, BrandNewAgenda) :-
 memberchk(Child,NewAgenda),
 addChildren(Others,Reverse_Path,Current,NewAgenda,Target,BrandNewAgenda).
bar(Reverse_Path, Child, [], BrandNewAgenda) :-
 BrandNewAgenda = [Child].
bar(Reverse_Path, Child, NewAgenda, BrandNewAgenda) :-
 New_Score =< FP,
 BrandNewAgenda = [Child|NewAgenda].
bar(Reverse_Path, Child, NewAgenda, BrandNewAgenda) :-
 append(NewAgenda, [Child], BrandNewAgenda).
main(Reverse_Path, BrandNewAgenda) :-
 foo(Reverse_Path, Child),
 bar(Reverse_Path, Child, [], BrandNewAgenda).

This is just a rough sketch, there are a lot of loose ends here like variables Others, Target or Result (I guess you are juggling too many variables anyway), but I hope you get the gist of it:

  • Decompose into multiple simpler predicates that encode alternatives through multiple clauses.
  • Bind results to "out" variables in the clause head (like Child in foo/2 or BrandNewAgenda in bar/4).
  • Compose the smaller predicates in a "main" predicate that glues them togehter.
answered Jun 28, 2020 at 16:11
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.