Higher-Order Functions in K? - kframework

Is it possible to write higher-order functions in K?
Particularly, things like Map and Fold, where I traverse a structure and apply a function to every element.
For example, if I have a list:
A ~> B ~> C
and I want to map a function F to every element of the list:
F A ~> F B ~> F C
Or maybe produce a fold:
F A (F B (F C))
where F is [function, functional] and is meant to evaluate, not be there syntactically.

If you know is advance what functions you want to be using in a higher order fashion, you can approximate this with something like:
syntax MapFunction ::= "foo"
syntax KItem ::= MapFunction "(" KItem ")" [function]
rule foo(...) => ...
syntax List ::= map(List, MapFunction) [function]
rule map(.List, _) => .List
rule map(ListItem(K) L, F) => ListItem(F(K)) map(L, F)
I recognize this is not ideal since it's not really a higher order function and you have to be explicitly aware of every function you intend to use this way and write it in a different fashion, but it's a decent workaround if you just need something quick and dirty in a couple places in the semantics.
As for the rest of your question, we would love to support higher order functions more generally, but we do not yet.

Related

How to show that a grammar with Bitwise operator is ambiguous using the expression a>>b^c

I am trying to solve this question but I really don't know how to get started. I would appreciate some help.
The bitwise operators for a language are shown in the table below alongside the grammar. The operators and the grammar rules are in order of precedence from highest to lowest. The characters a, b and c represent terminals in the language.
Grammar table:
Show that the grammar is ambiguous using expression: a >> b ^ c
Rewrite the grammar so that it is unambiguous.
The Dragon Book says: "A grammar that produces more than one parse tree for some sentence is said to be ambiguous." So to show that a grammar is ambiguous, you need to show at least two parse trees for a single sentence generated by the grammar. In this case, the sentence to use is already given to you, so for Q1 you just need to find two different parse trees for a >> b ^ c. Shiping's comment gives you a big clue for that.
For Q2, where they ask you to "rewrite the grammar", I suspect the unspoken requirement is that the resulting grammar generate exactly the same language as the original. (So Shiping's suggestion to introduce parentheses to the language would not be accepted.) The general approach for doing this is to introduce a nonterminal for each precedence level in the precedence chart, and then modify the grammar rules to use the new nonterminals in such a way that the grammar can only generate parse trees that respect the precedence chart.
For example, look at the two trees you found for Q1. You should observe that one of them conforms to the precedence chart and one does not. You want a new grammar that allows the precedence-conforming tree but not the other.
As another clue, consider the difference between these two grammars:
E -> E + E
E -> E * E
E -> a | b
and
E -> E + T
T -> T * F
F -> a | b
Although they generate the same language, the first is ambiguous but the second is not.

Elm syntax help required

Could you please explain me what does mean in Elm next statement?
(=>) = (,)
I found it in the example of Elm architecture tutorial
This is infix notation. In effect, this defines a function
(=>) = \a b -> (a,b)
Infix is then used without the brackets, so
a => b == (a,b)

Correct use of findall/3, especially the last result argument

I'm a beginner in Prolog and I am dealing with a problem that might seem stupid to you, but I really can't understand what I'm doing wrong! Ok, I have this file fruits.pl and inside that I have something like this:
fruit(apple,small,sweet).
fruit(lemon,small,nosweet).
fruit(melon,big,sweet).
I have already (inside that file made a coexist(X,Y) atom that checks if two fruits can be put together in a plate. It works fine! But now I can't create a suggest(X) that takes as a parameter a fruit and returns a list of fruits that can be put together in the same plate.
The thing is I was trying to make something like that
suggest(X) :- findall(Y,fruit(Y,_,_), List), coexist(X,Y).
What do you think? Every time I try to run this in swi prolog there is a warning 'singleton variable' and when I press
suggest(apple).
then it says false..
sorry for my english :/
Predicates in Prolog do not return anything. You have goals that are satisfied or not and you can interpret that as returning true or false.
Your predicate suggest(X) should contain another parameter that will be bound to the list of fruits that go together with X. An option would be: suggest(X, List) which describes the following relation: List represents all the fruits that go together with X. Then, you could ask:
?- suggest(apple, List).
List = [pear, cherry].
The goal findall(Y, ... , ...) uses the Y variable internally and Y is still unbound after the goal is satisfied. So, you should move coexist(X,Y) inside the second argument of findall/3 which is the goal that is satisfied in all possible ways. Th rule below works only if X is instantiated (suggest(+X, -List)).
suggest(X, List) :- findall(Y, (fruit(Y,_,_), coexist(X, Y)), List).
You can read this as follows: "List represents all fruits Y that coexist with X".
When you try to define a predicate in Prolog, first of all pretend that you have written that predicate already and start with imagining how you would use it. That is, what queries you would like to pose.
To me, it looks as if coexist/2 already describes what you want. BTW, may_coexist/2 might be a more descriptive name. Why do you want this in a separate list? And why using fruit/3 at all? But for the sake of the question let's assume that this makes sense. So essentially you would have now a relation fruit_compatible/2:
fruit_compatible(F, G) :-
fruit(F, _, _),
may_coexist(F, G),
fruit(G, _, _). % maybe you want to add this?
And now, let's assume you want this list too. So you would have a relation fruit_suggestions/2. How to use it?
?- fruit_suggestions(apple, L).
L = [cherry,pear].
or ... should it be rather L = [pear,cherry]? Or both?
?- fruit_suggestions(lemon, L).
L = [orange].
So every time I want a suggestion I have to think of a fruit. Always thinking: what fruit should it be? Fortunately there is a less demanding way in Prolog: Simply use a variable instead of the fruit! Now we should get all suggestions at once!
?- fruit_suggestions(F, L).
F = apple, L = [cherry, pear]
; F = lemon, L = [orange]
; F = cromulon, L = [embiggy, mushfruit].
So we need to implement it such that it will behave that way. findall/3 alone does not solve this. And implementing it manually is far from trivial. But there is setof/3 which handles variables in exactly that manner. Many of the tiny nitty-gritty design decisions have already been made, like that the list will be sorted ascendingly.
fruit_suggestions(F, L) :-
setof(G, fruit_compatible(F, G), L).
Edit: Due to the discussion below, here would be a solution that also permits empty lists. Note that this sounds trivial but it is not. To see this, consider the query:
?- fruit_suggestions(F, []).
What does it mean? What should F be? Also things that are no fruits at all? In that case we would have to produce solutions for everything. Like F = badger ; F = 42 ; .... Most probably this does not make much sense. What might be intended is those fruits that are incompatible with everything. To this end, we need to add a new rule:
fruit_suggestions(F, []) :-
setof(t,X^Y^fruit(F,X,Y),_),
\+ fruit_compatible(F, _).
fruit_suggestions(F, L) :-
setof(G, fruit_compatible(F, G), L).

Are there any right associative short-circuit operators

I'm working on a interrupter the lets one define their own operators. The goal then is to take an AST that looks like exp op exp op exp and turn it into either exp op (exp op exp) or (exp op exp) op exp based on the relative precedence and associativity of the two operators. The language is dynamic so the only way to know what version of the operator to use is to evaluate the first expression and ask it what version of op to use.
On the other hand, it is important that we not evaluate the second expression because if op is || (as commonly used) then we should be able to short-circuit if the first exp is false.
a problem would arise if some operator were both right associative and short-circuiting. My question is are there any right associative, short-circuiting operators in common use (for a chosen value of "common")?
N.b. assignment is handled separately by the parser so = is not an operator and a (op)= b is syntactic sugar for a = a op b.
Boolean implication might be.
I would probably read
a → b → c
as "a implies that b implies c" which would suggest that it should parenthesize
a → (b → c)
and boolean implication should probably be short-circuiting since when a is false then the right side of (a → b) is irrelevant to the result.

What is the name of a [foo, bar] = ["foo", "bar"] feature?

I need to know a correct name for this cool feature that some languages provide.
FYI: In some languages it is possible to do a multiple assignments by assigning a structure of values to a structure of "variables". In the example in the question title it assigns "foo" to foo and "bar" to bar.
It's generally called destructuring bind in functional languages (which don't have assignments) and destructuring assignment in imperative languages.
Some languages provide subsets of that feature and then call it something different. For example, in Python it works with Tuples, Lists or Sequences and is called Tuple unpacking, List unpacking or Sequence unpacking, in Ruby, it works with Arrays (or objects that are convertible to an array) and is called parallel assignment.
Destructuring bind can get arbitrarily complex. E.g. this (imaginary) bind
[Integer(a), b, 2, c] = some_array
would assign the first element of some_array to a, the second element to b and the fourth element to c, but only if the first element is an Integer, the third element is equal to 2 and the length is 4. So, this even incorporates some conditional logic.
Destructuring bind is a subset of more general pattern matching, which is a standard feature of functional languages like Haskell, ML, OCaml, F#, Erlang and Scala. The difference is that destructuring bind only lets you take apart a structure and bind its components to variables, whereas pattern matching also matches on values inside those structures and lets you make decisions and in particular lets you run arbitrary code in the context of the bindings. (You can see the above imaginary bind as half-way in between destructuring bind and pattern matching.)
Here's the classical example of a reverse function in an imaginary language, written using pattern matching:
def reverse(l: List): List {
match l {
when [] { return [] }
when [first :: rest] { return (reverse(rest) :: first) }
}
}
In Python it is known as list or sequence unpacking: http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences
my_list = ["foo", "bar"]
foo, bar = my_list
It's called parallel assignment in Ruby and other languages.
Perl and PHP call it list assignment
Perl:
my ($foo, $bar, $baz) = (1, 2, 3);
PHP:
list($foo, $bar, $baz) = array(1, 2, 3);
If you view the right hand side as a tuple, one could view the assignment as a kind of Tuple Unpacking.
In Erlang it's ... well, it's not assignment, it's pattern matching (seeing as there is no assignment, as such, in Erlang).
$ erl
Erlang R14B (erts-5.8.1) [source] [64-bit] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:true]
Eshell V5.8.1 (abort with ^G)
1> [H1, H2, H3| Rest] = [1,2,3,4,5].
[1,2,3,4,5]
2> H1.
1
3> H2.
2
4> H3.
3
5> Rest.
[4,5]
Why is it called "pattern matching"? Because it actually is matching patterns. Look:
6> [1,2,3,4,A] = [1,2,3,4,5].
[1,2,3,4,5]
7> A.
5
8> [1,2,3,4,A] = [1,2,3,4,6].
** exception error: no match of right hand side value [1,2,3,4,6]
In the first one we did what effectively amounts to an assertion that the list would start with [1,2,3,4] and that the fifth value could be anything at all, but please bind it into the unbound variable A. In the second one we did the same thing except that A is now bound so we're looking explicitly for the list [1,2,3,4,5] (because A is now 5).
Mozilla calls it destructuring assignment. In Python, it's sequence unpacking; tuple unpacking is a common special case.
In Clojure it would be called destructuring. Simple example:
(let [[foo bar] ["foo" "bar"]]
(println "I haz" foo "and" bar))
It's also often used in function definitions, e.g. the following destructures a single point argument into x and y components:
(defn distance-from-origin [[x y]]
(sqrt (+ (* x x) (* y y))))
You can also use the same technique to destructure nested data structures or key/value associative maps.