Returning a value from a function in prolog - function

How do we return a value from a Prolog function that takes only one argument? Ex. leaf(V) is a function which should return a value V and it is called from a function tree(leav(V), sum)?

Prolog doesn't have "functions", it has "predicates". I.e. they are a description of a relationship between terms. A predicate can only evaluate to "true" or "false".
However, the way a predicate evaluates to true or false is by unification, i.e. prolog tries to find instances for the variables from the existing knowledge base (i.e. your source code) that will make that predicate true.
Therefore you can trick a prolog predicate of the form Pred(In, Out), such that, for a given "In" prolog could unify "Out" with the right value that makes the predicate true.

Prolog does not have function evaluation, so you will have to represent your function as a relation
f(In,Out) :- ... define the relationship between In and Out in the body ...
For example for squaring:
square(X,Y) :- Y is X*X.
?- square(12,X).
X=144
The "function symbols" in Prolog are purely denotational: they are for constructing terms:
f(x)
The above term has no inherent meaning or resolvability. It is just a term, more precisely a tree
f
|
x

Related

why aren't anonymous functions in Lua expressions?

Can anyone explain to me why the anonymous function construct in Lua isn't a fully fledged expression? To me this seems an oddity: it goes (slightly) against the idea that functions should be first class objects, and is (not often but occasionally) an inconvenience in what is mostly a really well-thought out and elegant language.
example, using the command line Lua, with workaround
Lua 5.3.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio
> function(x) return x*x end (2)
stdin:1: <name> expected near '('
> square = function(x) return x*x end
> square(2)
4
Lua's function call syntax has some syntactic sugar built into it. You can call functions with 3 things:
A parenthesized list of values.
A table constructor (the function will take the table as a single argument).
A string literal.
Lua wants to be somewhat regular in its grammar. So if there's a thing which you can call as a function in one of these ways, then it should make sense to be able to call it in any of these ways.
Consider the following code:
local value = function(args)
--does some stuff
end "I'm a literal" .. foo
If we allow arbitrary, unparenthesized expressions to be called just like any other function call, then this means to create a function, invoke it with the string literal, concatenate the result of that function call with foo, and store that in value.
But... do we actually want that to work? That is, do we want people to be able to write that and have it be valid Lua code?
If such code is considered unsightly or confusing, then there are a few options.
Lua could just not have function calls with string literals. You're only saving 2 parentheses, after all. Maybe even don't allow table constructors as well, though those are less unsightly and far less confusing. Make everyone use parentheses for all function calls.
Lua could make it so that only in the cases of lambdas are function calls with string literals prevented. This would require substantially de-regularizing the grammar.
Lua could force you to parenthesize any construct where calling a function is not an obviously intended result of the preceding text.
Now, one might argue that table_name[var_name] "literal" is already rather confusing as to what is going on. But again, preventing that specifically would require de-regularizing the grammar. You'd have to add in all of these special cases where something like name "literal" is a function call but name.name "literal" is not. So option 2 is out.
The ability to call a function with a string literal is hardly limited to Lua. JavaScript can do it, but you have to use a specific literal syntax to get it. Plus, being able to type require "module_name" feels like a good idea. Since such calls are considered an important piece of syntactic sugar, supported by several languages, option #1 is out.
So your only option is #3: make people parenthesize expressions that they want to call.
Oh I see.. round brackets are needed, sorry.
(function(x) return x*x end) (2)
I still don't see why it is designed like that.
Short Answer
To call a function, the function expression must be either a name, an indexed value, another function call, or an expression inside parentheses.
Long Answer
I don't know why it's designed that way, but I did look up the grammar to see exactly how it works. Here's the entry for a function call:
functioncall ::= prefixexp args | prefixexp ‘:’ Name args
"args" is just a list of arguments in parentheses. The relevant part is "prefixexp".
prefixexp ::= var | functioncall | ‘(’ exp ‘)’
Ok, so we can call another "functioncall". "exp" is just a normal expression:
exp ::= nil | false | true | Numeral | LiteralString | ‘...’ | functiondef | prefixexp | tableconstructor | exp binop exp | unop exp
So we can call any expression as long as it's inside parentheses. "functiondef" covers anonymous functions:
functiondef ::= function funcbody
funcbody ::= ‘(’ [parlist] ‘)’ block end
So an anonymous function is an "exp", but not a "prefixexp", so we do need parentheses around it.
What is "var"?
var ::= Name | prefixexp ‘[’ exp ‘]’ | prefixexp ‘.’ Name
"var" is either a name or an indexed value (usually a table). Note that the indexed value must be a "prefixexp", which means a string literal or table constructor must be in parentheses before we can index them.
To sum up: A called function must be either a name, an indexed value, a function call, or some other expression inside parentheses.
The big question is: Why is "prefixexp" treated differently from "exp"? I don't know. I suspect it has something to do with keeping function calls and indexing outside the normal operator precedence, but I don't know why that's necessary.

How to turn prolog predicates into JSON?

I wonder if there's a way to return a JSON object in SWI-Prolog, such that the predicate names become the keys, and the instantiated variables become the values. For example:
get_fruit(JS_out):-
apple(A),
pear(P),
to_json(..., JS_out). # How to write this part?
apple("Gala").
pear("Bartlett").
I'm expecting JS_out to be:
JS_out = {"apple": "Gala", "pear": "Bartlett"}.
I couldn't figure out how to achieve this by using prolog_to_json/3 or other built-in functions. While there are lost of posts on reading Json into Prolog, I can't find many for the other way around. Any help is appreciated!
Given hard coded facts as shown, the simple solution is:
get_fruit(JS_out) :- apple(A), pear(P), JS_out = {"apple" : A, "pear": B}.
However, in Prolog, you don't need the extra variable. You can write this as:
get_fruit({"apple" : A, "pear": B}) :- apple(A), pear(P).
You could generalize this somewhat based upon two fruits of any kind:
get_fruit(Fruit1, Fruit2, {Fruit1 : A, Fruit2 : B}) :-
call(Fruit1, A),
call(Fruit2, B).
With a bit more work, it could be generalized to any number of fruits.
As an aside, it is a common beginner's mistake to think that is/2 is some kind of general assignment operator, but it is not. It is strictly for arithmetic expression evaluation and assumes that the second argument is a fully instantiated and evaluable arithmetic expression using arithmetic operators supported by Prolog. The first argument is a variable or a numeric value. Anything not meeting these criteria will always fail or generate an error.

Fortran elemental function - is this behavior normal?

Consider the following function
ELEMENTAL FUNCTION int2str(i) RESULT(s)
INTEGER, INTENT(IN) :: i
CHARACTER(LEN = 50) :: appo
CHARACTER(LEN = :), ALLOCATABLE :: s
WRITE(appo, '(I0)') i
ALLOCATE(s, source = TRIM(appo))
END FUNCTION int2str
The function, being elemental, is a scalar function (in my case it takes one scalar integer and gives back one scalar character, even though allocatable in length) that applies elementwise to arrays.
Why the output of
print *, '>>>'//int2str([1, 3, 5, 7])//'<<<'
is (unexpectedly to me)
>>>1<<<>>>3<<<>>>5<<<>>>7<<<
whereas the output of
print *, '>>>', int2str([1, 3, 5, 7]), '<<<'
is (expectedly)
>>>1357<<<
?
What I mean is that the function should apply to every one of the four scalar integers composing the array, thus returning a length-4 array each element of which being a string, but it seems to me that its elementwise-ness applies to the whole concatenation of three strings, as though the // operator has precedence over the function's result.
For character concatenation, the expression
'>>>'//['1','3','5','7']
depends on the scalar '>>>' and the array ['1','3','5','7']. As with other intrinsic binary operations where the operands are a scalar and a rank-1 array, the expression is a rank-1 array.
In determining the value of the expression, the scalar operand is treated as an array like
['>>>','>>>','>>>','>>>']
and the expression is equivalent to
['>>>','>>>','>>>','>>>'] // ['1','3','5','7']
Finally, the expression has value where the elements are operands pairwise:
['>>>1','>>>3','>>>5','>>>7']
You can see the parallels with the expression
9+[1,3,5,7] ! [9,9,9,9]+[1,3,5,7] --> [10,12,14,16]
When there are two concentation operations going on, the obvious value is the result.
Note that I didn't express this in terms of an elemental function's result. This is partly because the fact the array comes from a function isn't significant. Also, your elemental function is not actually allowed: an elemental function result may not be allocatable.
On the invalid function, Vladimir F has submitted a bug report covering gfortran not detecting violation of the numbered constraint C1290 of Fortran 2008. In that report you can see that if you remove the result(s) and declare int2str as having the allocatable attribute the function is rejected. Some other compilers do already detect violation.
I've surprisingly experienced that result which I didn't expect (>>>1<<<>>>3<<<>>>5<<<>>>7<<<) is indeed the same even if I manually implement the ELEMENTALity of the function, namely
print *, '>>>'//[num2str(1), num2str(3), num2str(5), num2str(7)]//'<<<'
so I was possibly misunderstanding my own words thus RETURNing a length-4 array each element of which being a string. The function is indeed returning an array of strings, and the concatenation applies to every element of the array (the element of the array being stick together without space in between just because they're strings of characters).

Arity constraint on Julialang function type

Is it possible to specify a type constraint on arity of a Julia function, something like:
function foo(bar::Function{1})
...
end
This definition gives me an error:
ERROR: too many parameters for type Function
What you are asking is not possible, since a Julia function does not have well-defined arity.
Consider
f(x) = "method 1"
f(x, y) = "method 2"
after which f may be invoked in two ways:
julia> f(0)
"method 1"
julia> f(0, 0)
"method 2"
What, then, is the arity of f? If you are seeking to change behaviour of the function depending on its arity, then you need to pass in the desired arity as an additional parameter. Otherwise, the arity check can probably be left out.
Most probably, the arity constraint is needed to ensure parameter correctness. This does not need to be done in the function signature, but can be done using parameter checks at the top of the function code. One method could be:
if !any(m->length(m.sig.parameters)==2, methods(bar))
error("bar must be callable with 2 parameters")
end
More detailed checks on the signature of bar are also possible.
The declared parameter types of the function foo are idiomatically used to direct optimization through type inference and multiple dispatch and less to validate parameters.
Note that using the internal structure of MethodTable and Method types is not official Julia spec and might be subject to change in future versions of Julia.

can if be a proper function rather than a special form

I finally started learning functional languages (emacs lisp) and it makes explicit distinction between functions and special forms such as flow control , for example if.
Is there a fundamental/theoretical reason why special forms are distinct from functions? do any languages provide functional if?
Thanks
With eager evaluation the distinction is required, languages with lazy evaluation (i.e. Haskell) if et al. can be functions.
Eager evaluation: The function's arguments are evaluated before calling the function, and only the results are passed to the function.
Lazy evaluation: A function's arguments evaluated if and only if they are accessed.
If if was a normal function, then both its arguments—the then form and the else form—would both be evaluated before calling the if function, because that's the rule of function evaluation: evaluate all arguments to produce values, then provide that sequence of values as arguments to the function designated by the first symbol in the list.
Instead, with if what you want to do is evaluate exactly one of the then form and else form, not both. In order to suppress evaluation of one or the other, you need either a macro or a special form.
In languages like Emacs Lisp and Common Lisp, special forms are built-in language constructs. They have different evaluation rules that normal function calls. For normal function calls all arguments are evaluated. So, you can't write an IF as a normal function - the condition determines which clause gets evaluated. Also usually you can't write your own special forms - in Common Lisp there is no language construct for defining a special form (though individual implementations must have implemented the existing ones somehow. This leads to macros. With macros you can write a syntactic transformation that transforms one expression into another one. To be able to write IF as a macro, you need to have another conditional form, which you can use for the transformed code. Lisp provides conditionals as basic constructs. Let's assume COND is such a basic construct, then you could expand IF into a usage of COND.
MY-IF as a macro in Common Lisp:
(defmacro my-if (condition true-clause false-clause)
`(cond (,condition ,true-clause)
(t ,false-clause)))
So
(my-if (foo-p) 'one 'two)
gets expanded into
(cond ((foo-p) 'one)
(t 'two))
For completeness: there are no special forms in the Pico language for example, and if is a primitive function while Pico is inspired by Scheme and has eager evaluation by default.
In Scheme you could write
(define (true t f)
(t))
(define (false t f)
(f))
(define (function_if c t e)
(c t e))
and then
(function_if true (lambda () 'true) (lambda () 'false))
==> true
What makes this manageable in Pico is that you can define functional parameters that take functional arguments that are "automatically" delayed. This means that you don't have to do the wrapping inside lambdas yourself. Pico therefore has eager evaluation but with lazy evaluation on demand, bypassing the need for special forms.
So, in Scheme syntax with functional parameters you can encode booleans as:
(define (true (t) (f))
(t))
(define (false (t) (f))
(f))
Then function if becomes:
(define (function_if c (t) (e))
(c (t) (e)))
and
(function_if true 'true 'false)
==> true
As another example, the definition of the function and is (define (and p (q)) (p (q) false)).
Similarly you can define or, not, while, for, ... as functions, using the above encoding of booleans.
Short answer: No.
Long(er) answer: (if ...) requires that you control the evaluation order of the arguments. Lisp, being an eager language cannot do this in a function.
Workaround: do it in a macro:
(defmacro _if (cnd true false)
(let ( (gcond (gensym))
(gresp (gensym)))
`(let ( (,gcond ,cnd) ;`#quotes
(,gresp nil))
(and ,gcond (setf ,gresp (multiple-value-list ,true)))
(and (not ,gcond) (setf ,gresp (multiple-value-list ,false)))
(values-list ,gresp))))
For example:
[dsm#localhost:~]$ clisp -q
[1]> (defmacro _if (cnd true false)
(let ( (gcond (gensym))
(gresp (gensym)))
`(let ( (,gcond ,cnd) ;`#quotes
(,gresp nil))
(and ,gcond (setf ,gresp (multiple-value-list ,true)))
(and (not ,gcond) (setf ,gresp (multiple-value-list ,false)))
(values-list ,gresp))))
_IF
[2]> (_if (= 1 1) (+ 2 3) "bar")
5
[3]> (_if (= 1 2) (+ 2 3) "bar")
"bar"
[4]>
In Scala it's possible to model if with correct side-effect evaluation using call-by-name arguments.
def If[A](cond : Boolean, truePart : => A, falsePart : => A) = if (cond) truePart else falsePart
These feature can be used to model lots of new control structures as well.
IF could be a function in a functional language having call-by-name semantics (lazy evaluation), as in Lambda Calculus or Algol. In fact that is, I think, at the heart of the relationship between Turing Machines and Lambda Calculus as equivalent foundations for computing. However, in languages having side-effects (like assignments to variables) it is not much use, because when things happen is important.