How to write `result?1:0` in OCaml? - functional-programming

in java we can write result?1:0. It is a short way to get a value depending on the result bool.
How can I write such a thing in OCaml?

It sounds like this is a duplicate question. However, note that everything in OCaml is an expression. So the answer is if result then 1 else 0. You may need to parenthesize this depending on the context. (In the C family, a form I sometimes use for your expression is !!result.)

Related

Knowing when what you're looking at must be a macro

I know there is macro-function, explained here, which allows you to check, but is it also possible in simply reading lisp source to sometimes infer of what you're looking at "that must be a macro"? (assuming of course you have never seen the function/macro before).
I'm fairly sure the answer is yes, but as this seems so fundamental, I thought worth asking, especially because any nuances on this may be valuable & interesting to know about.
In Paul Graham's ANSI Common Lisp, p70, he is describing how to use defstruct.
When I see (defstruct point x y), were I to know absolutely nothing about what defstruct was, this could just as well be a function.
But when I see
(defstruct polemic
(subject "foo")
(effect "bar"))
I know that must be a macro because (let's assume), I also know that subject and effect are undefined functions. (I know that because they error with undefined function when called 'at the top level'(?)) (if that's the right term).
If the two list arguments to defstruct above were quoted, it would not be so simple. Because they're not quoted, it must be a macro.
Is it as simple as that?
I've changed the field names slightly from those used on the book to make this question clearer.
Finally, Graham writes:
"We can specify default values for structure fields by enclosing the field name and a default expression in a list in the original definition"
What I'm noticing is that that's true but it is not a (quoted) list. Would any readers of this post have phrased the above sentence at all differently (given that macros haven't been introduced in the book yet (though I have a basic awareness of what they are)).
My feeling is it's not a "data list" those default expressions are enclosed in. (apologies for bad terminology) - seeking how rightly to conceptualise here.
In general, you're right: if there's some nesting inside the call and you are sure that the car's of the nested lists aren't functions - it's a macro.
Also, almost always, def-something and with-something are macros.
But there's no guarantee. The question is, what are you trying to accomplish? Some code walking/transformation or external processing (like in an editor). For the latter, you should keep in mind that full control is possible only if you perform code evaluation, although heuristics (like in Emacs) can take you pretty far. Or you just want to develop your intuition for faster code reading...
There is a set of conventions that identify quite cleary what forms are supposed to be macros, simply by mimicking the syntax of existing macros or special operators of CL.
For example, the following is a mix of various imaginary macros, but even without knowing their definition, the code shouldn't be too hard to figure out:
(defun/typed example ((id (integer 0 10)))
(with-connection (connection (connect id))
(do-events (event connection)
(event-case event
(:quit (&optional code) (return code))))))
The usual advice about macros is to avoid them if possible, so if you spot something that doesn't make sense as a lisp expression, it probably is, or is enclosed in, a macro.
(defstruct point x y)
[...] were I to know absolutely nothing about what defstruct was, this could just as well be a function.
There are various hints that this is not a function. First of all, the name starts with def. Then, if defstruct was a function, then point, x and y would all be evaluated before calling the function, and that means the code would be relying on global variables, even though they are not wearing earmuffs (e.g. *point*, *x*, *y*), and you probably won't find any definition for them in the preceding forms (or later in the same compilation unit). Also, if it was a function, the result would be discarded directly since it is not used (this is a toplevel form). That only indicates the probable presence of side-effects, but still, this would be unusual.
A top-level function with side-effects would look like this instead, with quoted data:
(register-struct 'point '(x y))
Finally, there are cases where you cannot easily guess if you are using a macro or a function:
(my-get object :slot)
This could be a function call, or you could have a macro that turns the above to (aref object 0) (assuming :slot is the zeroth slot in object, because all your objects are assumed to be of a certain custom type backed by a vector). You could also have compiler macros. In case of doubt, try to macroexpand it and look at the documentation.

Get the name of the calling predicate

Suppose I am working on this toy example (the point of the question is obviously not to solve this example):
p([]).
p([H|T]) :- H = 0, call_predicate(p,T).
call_predicate(Name,Arg) :- call(Name,Arg).
So far so good. Now let's say I want to add a predicate call_predicate/1 where I wouldn't need the name of the predicate:
call_predicate(Arg) :- Name = ??, call(Name,Arg).
So that I could use in p: call_predicate(T), implicitly knowing that I want to call the predicate of the same name.
The question is then how can I retrieve the name p from call_predicate/1, knowing that it is the name of the predicate that called call_predicate/1?
A similar question would be, if it's easier than the first one, how can I retrieve the name of the current predicate I am in at a time in the execution?
In SWI-Prolog check out library(prolog_stack).
In particular, a combination of the following predicates should give you what you want:
get_prolog_backtrace/2
prolog_stack_frame_property/2
Beware though: This is not readily portable to other Prolog systems, and in all likelihood there are more elegant and also more efficient ways to do what you need.
For example, one way to do what you are describing is to use term_expansion/2: You can expand specific goals in such a way that one of the arguments denotes the calling context. This is much more portable, very efficient at run time, and you can statically check the resulting expansion.

Why doesn't SML allow if-then without else?

In Standard ML, what was the reasoning behind having if-then-else as a single expression and not allowing only if-then without else clause?
Is it possible to write conditional statements in SML without the else clause?
Standard ML programs are expressions, not statements.
Standard ML is a functional programming language with some impure features. Programs written in Standard ML consist of expressions to be evaluated, as opposed to statements or commands [as found in C-like languages] ..
As such, because if-then-else is an expression, it must evaluate to a value. If the else was not required then the expression would effectively "have no value" if the condition failed - but by definition of an expression, it must have a value. Requiring an explicit else ensures that the expression will evaluate to value in both cases1.
Furthermore, the type from the then and else expressions must be unified - this will be the type of the entire if-then-else construct.
That is, if-then-else in SML is like the ternary (?:) operator in C-like languages, which also shares this "restriction". It is not equivalent if-statements whose branches are evaluated for side effects only.
1 Not all functional-like languages require an explicit then expression and some will default to a particular value. However, this is just how it works in SML which makes sense because there need not be a "default value" for any particular type and the resulting types must be unified.
This isn't specific to Standard ML; many or most languages with if-then-else expressions require an else-expression. For example, in C-like languages (C, C++, C#, Java, D, Perl, JavaScript, PHP, etc.), the expression takes the form cond ? expr_if_true : expr_if_false; in Visual Basic the Iif function requires both an expression-if-true and an expression-if-false; and so on. (There are some languages, such as the Excel formula language, that do not require both values, and substitute a default for the else-expression, but SML is hardly exceptional in not doing so.)
Is it possible to write conditional statements in SML without the else clause?
SML doesn't have any concept of "statements", let alone "conditional statements". It has declarations, but it doesn't make sense to declare something only conditionally (since type information is all determined at compile-time, whereas conditions of course can't be evaluated until run-time).
If you want to take a certain action when a condition is true, and take no action when the condition is false, you just need to use a conditional expression where only the then-expression has a side effect. For example:
val _ = if i > 30 then print "i is too big!" else ()
(where print "Yay!" and () are both expressions of type unit).
I understand what you are saying, but if the "if" statement of your function returns false then the program doesn't know what to do. You probably just want the function to keep going if the expression is false....right?
If you want that to happen then you have make your "else" do something that just passes on to the rest of the function.
I actually don't know much about SML so i couldn't tell you how to do that
Because otherwise, what would be the value of the expression if the if branch does not match? To not need the else branch would require a default value can be inferred. The only thing I see which could make sense, is to raise an exception. Could have been an option for the design of SML, but this was not and would not have been a lot relevant any way.
Whenever you feel there is no valid expression value on else, then just say something like this:
val x =
if condition then expression
else raise Domain;

Conditional function in APL

Is there a symbol or well-known idiom for the conditional function, in any of the APL dialects?
I'm sure I'm missing something, because it's such a basic language element. In other languages it's called conditional operator, but I will avoid that term here, because an APL operator is something else entirely.
For example C and friends have x ? T : F
LISPs have (if x T F)
Python has T if x else F
and so on.
I know modern APLs have :If and friends, but they are imperative statements to control program flow: they don't return a value, cannot be used inside an expression and certainly cannot be applied to arrays of booleans. They have a different purpose altogether, which is just fine by me.
The only decent expression I could come up with to do a functional selection is (F T)[⎕IO+x], which doesn't look particularly shorthand or readable to me, although it gets the job done, even on arrays:
('no' 'yes')[⎕IO+(⍳5)∘.>(⍳5)]
no no no no no
yes no no no no
yes yes no no no
yes yes yes no no
yes yes yes yes no
I tried to come up with a similar expression using squad ⌷, but failed miserably on arrays of booleans. Even if I could, it would still have to embed ⎕IO or an hardcoded 1, which is even worse as far as readability is concerned.
Before I go ahead and define my own if and use it on every program I will ever write, is there any canon on this? Am I missing an obvious function or operator?
(Are there any APL programmers on SO? :-)
The trouble with these:
(f t)[x]
x⌷f t
x⊃f t
is that both t and f get evaluated.
If you want to short-circuit the thing, you can use guards:
{x:t ⋄ f}
This is equivalent to
if (x) {
return t;
}
f;
in a C-like language.
Yes, there are APL programmers on SO (but not many!).
I think the answer is that there is no standard on this.
For a scalar solution, I use "pick":
x⊃f t
While for a Boolean array I use indexing as you do above:
f t[x]
I always use index origin zero, so there is no need to add 1, and the parens are not needed.
If these are not simple enough, I think you have to cover them with a function named "if". That will also let you put the true and false in the perhaps more natural ordering of t f.
In Dyalog APL you can use:
'value if true' (⊣⍣condition) 'value if false'
The idea is applying ⊣ (left tack – which always returns its left argument, while discarding the right argument) either 0 (for false) or 1 (for true) times – to the right argument. So, if it is applied 0 time (i.e. not at all), the right argument is returned unmodified, but if it is applied (once), then the left argument is applied. E.g.:
a b←3 5
Conditional←⊣⍣(a=b)
'match' Conditional 'different'
different
a b←4 4
Conditional←⊣⍣(a=b)
'match' Conditional 'different'
match
or
Cond←{⍺(⊣⍣⍺⍺)⍵}
bool←a=b
'match'(bool Cond)'different'
match
An old, old idiom which did something like C's ternary operator ? : and returned a result was the following:
r←⍎(¯3 3)[x=42]↑'6×8 ⋄ 6×7'
Note that this is written for origin 0 and the parens around the -3 3 are there for clarity.
x=42 evaluates to zero or one, depending on this answer we choose -3 or 3, and thus select and execute either the first 3 elements ("6x8") or last 3 elements ("6x7") of the string. The diamond ⋄ is just there for decoration.
Needless to say, one would probably not code this way if one had :if :else avaiable, though the control structure form would not return a result.
This is a common question, I think the reason there is no standard answer to it is that for the things you do with APL, there is actually less need for it than other languages.
That said, it is sometimes needed, and the way I implement an IFELSE operator in GNU APL is using this function:
∇Z ← arg (truefn IFELSE falsefn) condition ;v
v←⍬
→(0=⎕NC 'arg')/noarg
v←arg
noarg:
→condition/istrue
Z←falsefn v
→end
istrue:
Z←truefn v
end:
∇
The function can be called like this:
3 {'expression is true' ⍵} IFELSE {'was false' ⍵} 0
was false 3
This particular implementation passes in the left-hand argument as ⍵ to the clause, because that can be handy sometimes. Without a left-hand argument it passes in ⍬.
The APL expression:
(1+x=0)⌷y z
should be the C language equivalent for
x?y:z
And all the others
(1+x>0)⌷y z
for
x<=0?y:z
Etc. In general if a b c are expressions of respective languages the APL expression:
(1+~a)⌷b c
It should be equivalent to the C language:
a?b:c

Predicates returning. Prolog

So I have the predicate which returns true several time.
% true returns several times and i need to press ';'
?- get_all_transformed_moves.
true ;
true ;
true.
Is the swi prolog have some method which can help me to run this predicate without typing';'?
% Wished version
?- get_all_transformed_moves.
true.
Consider the following:
likes(prolog).
likes(haskell).
likes(erlang).
likes_something:-
likes(_Something).
if now you ask:
?- likes_something.
you will get
true ;
true ;
true.
this happens because prolog finds three ways to satisfy the likes_something/0 predicate (with prolog, haskell and erlang) so it answers true for three times.
this isn't exactly a problem; at any time you can press and prolog will stop trying to find answers (this is quite handy when there are a lot of results).
the same thing happens to your predicate: there are three solutions and by pressing ; you force prolog to find them all. as Rocha suggested you could use findall/3. For example, you could write:
likes_something:-
findall(X, likes(X), _).
and this will return just one yes
however, it doesn't offer more information than the previous version; instead it hides the fact that there are 3 solutions and wastes time trying to find more while the answer wont change.
For that reason I think that you should use findall/3 if you actually want to see the results:
likes_all(L):-
findall(X,likes(X),L).
of course, the decision of whether you need to see the results or not is up to you (or rather to the problem you are trying to solve :p)
another option is to use a cut: !/0
for example:
likes_something:-
likes(_Something),
!.
this will stop prolog from searching for more solutions and you will get just one true.
note however that cuts can be tricky.
All in all:
if you want prolog to search for all the answers (if you decide to put them in a list or you have side-effects in your predicates or if you just want it): use findall/3
if you don't want to have the option to search for more answers: use a cut (!/0)
else just press enter instead of ;
You can use the findall/3 predicate:
findall(Object,Goal,List).
produces a list List of all the objects Object that satisfy the goal Goal. Often Object is simply a variable, in which case the query can be read as: Give me a list containing all the instantiations of Object which satisfy Goal.
I suppose that is what you want.
If you want the predicate to succeed at most once, then you can use once/1 provided with SWI.
In your example:
?- once(get_all_transformed_moves).
true.

Resources