/* Send an unknown method call (Rosetta code) in Picat. http://rosettacode.org/wiki/Send_an_unknown_method_call """ Invoke an object method where the name of the method to be invoked can be generated at run time. """ This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ main => go. go => % functions (using apply) % parse_term/1 converts to an atom Name1 = "sum", Sum1 = apply(parse_term(Name1),1..10), println(Sum1), Name2 = sum, Sum2 = apply(Name2,1..10), println(Sum2), Name3 = $sum, % structure Sum3 = apply(Name3,1..11), println(Sum3), Name3b = $sum(1..12), % structure Sum3b = apply(Name3b), println(Sum3b), Name3c = $sum(1..13), % structure Sum3c = apply(Name3c.name,Name3c[1]), println(Sum3c), Name4 = "+", Sum4 = apply(parse_term(Name4),1,10), println(Sum4), Name4b = length, Sum4b = apply(Name4b,[1,2,3,10]), println(Sum4b), Name5 = +, Sum5 = apply(Name5,1,10), println(Sum5), % predicates (using call) Name6 = "prime", if call(parse_term(Name6),11) then println(prime) else println(no_prime) end, Name7 = prime, if call(Name7,12) then println(prime) else println(no_prime) end, nl. % For functions: appply % For predicates: call % The first parameter to apply/n and call/n must be an atom. % Strings can be converted to atoms via to_atom/1 (or parse_term/1). go2 => println("Function: Use apply/n"), Fun = "fib", A = 10, % Convert F to an atom println(apply(to_atom(Fun),A)), nl, println("Predicate: use call/n"), Pred = "pyth", call(Pred.to_atom,3,4,Z), println(z=Z), nl, % Pred2 is an atom so it can be used directly with call/n. Pred2 = pyth, call(Pred.to_atom,13,14,Z2), println(z2=Z2), nl, % println(parse_term("12**2+15**2").apply), nl. % A function fib(1) = 1. fib(2) = 1. fib(N) = fib(N-1) + fib(N-2). % A predicate pyth(X,Y,Z) => Z = X**2 + Y**2.