Advertisement
Guest User

Prolog code generator

a guest
Jul 23rd, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. % separators
  2. separator(" ").
  3. separator(",").
  4. separator(";").
  5. separator("|").
  6.  
  7. % operators
  8. safe_op(string_upper).
  9. safe_op(string_lower).
  10. safe_op(string_length).
  11. safe_op(number_string).
  12. safe_op(reverse).
  13. safe_op(str_split(Sep)) :- separator(Sep).
  14. safe_op(str_join(Sep)) :- separator(Sep).
  15.  
  16. map_op(maplist(Op)) :- safe_op(Op).
  17.  
  18. known_op(X) :- safe_op(X).
  19. known_op(X) :- map_op(X).
  20.  
  21.  
  22. % Check whether Input can become Output in N steps by
  23. % using the list of code in the last argument.
  24. %
  25. % ?- run_test("I am Robert","Robert am I",3,X).
  26. % X = [str_split(" "), reverse, str_join(" ")] .
  27. run_test(Input,Input,0,_).
  28. run_test(_,_,0,_) :-
  29.     !,fail. % we ran out of steps
  30. run_test(Input,Output,1,[HCode]) :-
  31.     known_op(HCode),
  32.     catch(call(HCode,Input,Output),_,fail).
  33. run_test(Input,Output,Nsteps,[HCode|TCode]) :-
  34.     known_op(HCode),
  35.     catch(call(HCode,Input,Intermed),_,fail),
  36.     NewNsteps is Nsteps - 1,
  37.     run_test(Intermed,Output,NewNsteps,TCode).
  38.  
  39.  
  40. % ?- run_test("a|b|c",["a","b","c"],1,[str_split("|")]).
  41. % true .
  42. str_split(Sep,In,Out) :-
  43.     split_string(In,Sep,"",Out).
  44.  
  45. % ?- run_test(["a","b","c"],"a|b|c",1,[str_join("|")]).
  46. % true .
  47. str_join(_,[H|[]],Out) :-
  48.     !,H = Out.
  49. str_join(Sep,[H|T],Out) :-
  50.     string_concat(H,Sep,HeadAndSep),
  51.     str_join(Sep,T,StringRest),
  52.     string_concat(HeadAndSep,StringRest,Out).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement