In Coq, why use Atom and how to construct it? - llvm

I'm currently working with vellvm, developing a transformation on it. I'm a coq newbie.
This is the atom implementation:
http://www.cis.upenn.edu/~plclub/popl08-tutorial/code/coqdoc/Atom.html
In vellvm, atoms are used as ids and labels, for example.
I would like to insert a block of code in one llvm transformation, and for that I would have to give a label of type "atom". How can I construct a Atom label?
Putting my question a bit more general:
1) Why someone would want to use Atom?
2) How can I construct one?
3) If I construct this way, will I have trouble taking in consideration that the atoms might be used differently in the code?
Thanks!
Edit: Code for id and labels
Definition id := atom. (*r identities *)
Definition l := atom. (*r labels *)

Looking at the file you pointed (by Chargueraud and Aydemir), you understand that the atom type is used to represent any type that you could use to give names to things.
The function atom_fresh_for_list should be used to create a new atom. The type of this function indicates that it returns not only an arbitrary atom, but also some proof that the atom you get is not present in the list you gave as argument. This is how you create a new one: you put all the old ones in a list, and you call the function atom_fresh_for_list with it as argument. As a result you obtain a value of type {x : atom | ...}. This is not exactly an atom: it is an atom with more information. You can get hold of the atom by writing:
let (v, h) := atom_fresh_for_list ... in ...
and then, in the second "...", the variable v contains the atom and you can use it. If you need to prove that this atom is a new one, then you can use the other variable h for that.
Yves

Yves was able to answer it partially, just don't have an example of how to construct a atom. You need to use projT1. Following are the code for this:
Definition an_atom : atom := (projT1 (atom_fresh_for_list nil)).
Where nil is any list.

Related

How can I change this if-then-else construction to a construction that uses pattern matching or/and guards?

I've been given the following exercise (one out of several that link together to pretty print a table and make selections in it):
Write a function select :: Field → Field → Table → Table that given a column name and a field value, selects only those rows from the table that have the given field value in the given column. If the given column is not present in the table then the table should be returned unchanged. (Hint: use the functions (!!), elemIndex, filter and maybe.)
And ended up with this solution:
select :: Field -> Field -> Table -> Table
select column value table#(header:rows) =
let i = fromMaybe (-1) (elemIndex column header)
in if i == (-1) then table
else header : filter (\r -> r !! i == value) rows
While it seems to be perfectly correct in its function - it works - I've been told that if-then-else constructions such as these are 'bad form' and should be avoided using guards (as should my use of fromMaybe using pattern matching).
How would I go about changing this into a 'better' style with pattern matching/guards?
One simple improvement that I immediately see when looking at your code is that it seems pointless to use fromMaybe to convert Nothing to -1, then simply do a check (whether with an if or with guards doesn't matter) on whether that value is -1. Why not check against Nothing in the first place?
I guess you might have been led this way by similar functions in other languages where if an index isn't found then -1 is returned as an artifical value (sometimes called a "sentinel value") to mean "the element wasn't found" - but in Haskell, Nothing communicates this much better.
Further Nothing can be pattern matched on, so rather than using if or guards, you can use a case statement. This turns your function into:
select :: Field -> Field -> Table -> Table
select column value table#(header:rows) =
case elemIndex column header of
Nothing -> table
Just i -> header : filter (\r -> r !! i == value) rows
This to my mind is much better than your original.
I still feel it could be improved further - in particular (!!) is rarely used in idiomatic Haskell code as it risks crashing if the index is out of bounds. It's also quite inefficient compared to the array-indexing operators of other languages (because Haskell lists are linked-lists, not arrays, and to get say the 100th element it has to run through the previous 99 rather than being able to do direct "random access"). However I don't see how you can really avoid that given what you have to work with here.
Replace
let i = fromMaybe (-1) (elemIndex column header)
in if i == (-1) then ... else ...
with
case elemIndex column header of
Nothing -> ... -- no index found
Just i -> ... -- index i found
Your original code suffers from "boolean blindness": you already have a useful value of type Maybe Int which tells you:
if there is no index (Nothing)
if there is an index, and what it is (Just i)
The last emphasized part is important! In your code you work hard to lose that information, reducing everything to a boolean telling you only:
if there is no index (True)
if there is an index, and nothing else (False)
Don't use booleans unless you really have to. Many languages must use if someBooleanCondition to conditionally branch. Haskell does not have to: we have case and pattern matching that combines branching and extracting information from each case (the i above).

How to group by elements of tuple in Scala and map to list of new elements?

I going through some Scala exercises in order to understand better high order functions. I have the following problem, which I cant understand how to solve. I have the following list:
val input = List((1,"a"), (1,"b"), (1,"c"), (2,"d"), (2,"y"), (2,"e"), (3, "u"), (3,"a"), (3,"d"))
I want to create a Map from this list which maps each letter encountered on the input list to a list of all the numbers which were previously in the same tuple as that letter. Example output:
Map(a -> List(1,3), b->List(1), c->List(1), d->List(2,3), y->List(2), e->List(2), u->List(3)
What I have tried so far is:
val output = input.groupBy(_._2)
However this gives as output:
Map(e -> List((2,e)), y -> List((2,y)), u -> List((3,u)), a -> List((1,a), (3,a)), b -> List((1,b)), c -> List((1,c)), d -> List((2,d), (3,d)))
Could someone help me understand how I could go about solving this? I appreciate any help as I am new to functional programming
As #sinanspd said:
input
.groupBy {
case (numer, letter) => letter
} map {
case (key, list) => key -> list.map {
case (number, letter) => number
}
}
// Or equivalently
input.groupBy(_._2).view.mapValues(list => list.map(_._1)).toMap
// Or even simpler if you have access to Scala 2.13
input.groupMap(_._2)(_._1)
Every time you want to transform some collection of values where the transformation is one to one, you just need a map, so in this case, you want to transform the values of the Map returned by the groupBy, which are Lists, and then you want to transform every element of those Lists to just return the first component of the tuple. So it is a map inside another map.
Also, the Scaldoc is your friend. Usually, there are many useful methods, like mapValues or groupMap.
Here is a more detailed explanation of my comment. This is what you need to do:
val output = input.groupBy(_._2).mapValues(_.map(_._1))
It is important to remember in functional programming we love pure functions. Meaning we will not have shady side effects and we like to stick to one function one purpose principle
This allows us to chain these pure functions and reason about them linearly. Why am I telling you this? While your instinct might be to look for or implement a single function to do this, don't
In this case, we first groupBy the key, and then map each value where we take the value List and map it to extract the _._1 of the tuple.
This is the best I could do, to make it sorted too , as I see the other responses are not sorted , maybe someone can improve this too:
import scala.collection.immutable.ListMap
ListMap(input.groupBy(_._2).mapValues(_.map(_._1)).toSeq.sortBy(_._1):_*)

How to find inside a list of lists a list with a single element

I have been trying to do a function that returns to me the first (or all it might work to but I do prefer just the first), element of a list of lists that is single, i mean:
[[x;y;z];[a;b;c];[a];[b]]
In this case I would like to get returned the a or [a] but I cant I tried to do a function something like:
let rec find_unit ll =
match ll with
| [x] -> [x]
and so on...
But every time I try something like this, I get in a recursion that never stops, or the function simple dont return the element. Can someone tell me how to do it properly? I still cant understand a lot of OCaml syntax... Just like in the example I dont know that to put in the line of |[x] -> [x], particularly the first [x].
Sorry for the question but I am destroying my code now and I cant find a solution.
Try decomposing your problem into smaller subproblems.
(1) Your problem overall looks like an instance of the more general 'find'-problem, which has already been solved. See the standard function List.find or (if you want to find them all... List.find_all. Both functions need a predicate to pick the right element(s) from the list.
(2) You need a way to determine if some list is a singleton. It's easy, use pattern-mathing.
let is_singleton xs = function
| [_] -> true
| _ -> false
(3) Now, combine the above and you'll get a solution.
A couple of observations on the code you give:
Your pattern needs to match the whole string ll, but the pattern you give seems to be intended to match just one element of ll. A pattern more like [x] :: rest is going to work better.
The way to avoid infinite recursion is always the same. First, make sure you check for the smallest possible input (the basis). For your problem this will be the case when ll is an empty list. Second, if you haven't found what you're looking for, continue the search on a smaller problem. In your case this will mean searching the tail of your list.
You also need to decide what to do when there is no element of the list like the one you're looking for. If you return [x] when you find it, you could return [] (say) if you don't find it. Or you could raise an exception like Not_found.
(As a side comment, lists and arrays are different things in OCaml. I removed the array tag, as your question seems to be about lists.)
Well all answers here helped me find a way to get the solution, and I am going to put it here because it might help someone else.
I used the function:
let is_single xs = function
| [_] -> true
| _ -> false
to do: let teste xs = List.filter(fun inner ->(is_single inner)inner)xs;; This teste function is returning to me a List of Lists with all single elements, so to get only one element inside of that lists i did: List.hd(List.hd teste xs)

How to fix the code errors in OCaml?

I'm new to OCaml,and have just found an on-line OCaml guide, http://try.ocamlpro.com/.
When it comes to lesson 5, I get trapped in some exercises. So, here is the problem:
fix all these let expressions in order to get the expected result at the end:
1.
let xy =
let x = 'x' and let y = 'y' in x ::[y]
2.
let ab =
let a = 'a'
let b = 'B' in Char.lowercase b
in a ::[b]
3.
let up = Char.uppercase in
big_xy = List.map up xy ;
big_ab = List.map up ab ;
big_ab # big_xy
PS:I know how to solve problem 1,and I post it here for the need of problem 3.For Problem 2 and 3,I can see where the problem is,but I can hardly figure out how to fix it.I'm a little confused about the compact "let...in" statement,and there is few resource I can refer to for such problem.
This is a completely wrong OCaml, indeed it is not an OCaml at all))
I'm just trying to guess what was your intention, so in the second code sample you have tried to bind to variables to some character values, then lowercase one of them and create a list of this two values.
Before you can understand, what is wrong with your code, you need to know something about OCaml's grammar.
There're several kinds of binding statements in OCaml, the first one is an expression and has the following pattern:
let «variable-name» = «expr-1» in «expr-2»
This means that you bind the result of evaluating «expr-1» to a «variable-name», so that you can use it inside «expr-2» (and only in «expr-2», it is its scope). «expr-2» can be another binding-expression on its own. Let's take some examples:
let a = 'a' in [a]
or
let a = 'a' in
let b = 'b' in
[a; b]
The second kind of bindings is a so called top-level binding, that is used when you're adding some definition to a module level (or an interactive top-level, that is the same). They look a little bit simplier, but they're not expressions. When I say that something is not an expression, I mean, mostly, that it can't be evaluated to a value. So, they have the following pattern:
let «variable-name» = «expr»
As you can see, there is no in part, only raw binding. You can use this statement to create a global constant, e.g.,
let pi = 4. *. atan 1.
Or, you can use it to bind a function to a name (in other words to write a function definition):
let circle_area radius = pi * radius ** 2.
Of course, inside a function you can use any expressions, including a binding expression:
let area_of_circles radii =
let areas = List.map circle_area radii in
List.fold_left (+.) 0. areas
I would like to note, that there're lots of good tutorials and textbooks, that can help you to learn OCaml very fast. You can find them at the OCaml tag page. I, personally, would suggest you to look at the 'OCaml from the very beginning' book.

Erlang - Can one use Lists:append for adding an element to a string?

Here is my function that parses an addition equation.
expr_print({num,X}) -> X;
expr_print({plus,X,Y})->
lists:append("(",expr_print(X),"+",expr_print(Y),")").
Once executed in terminal it should look like this (but it doesn't at the moment):
>math_erlang: expr_print({plus,{num,5},{num,7}}).
>(5+7)
Actually one could do that, but it would not work the way wish in X in {num, X} is a number and not string representation of number.
Strings in Erlang are just lists of numbers. And if those numbers are in wright range they can be printed as string. You should be able to find detail explenation here. So first thing you wold like to do is to make sure that call to expr_print({num, 3}). will return "3" and not 3. You should be able to find solution here.
Second thing is lists:append which takes only one argument, list of list. So your code could look like this
expra_print({num,X}) ->
lists:flatten(io_lib:format("~p", [X]));
expr_print({plus,X,Y})->
lists:append(["(", expr_print(X),"+",expr_print(Y), ")"]).
And this should produce you nice flat string/list.
Another thing is that you might not need flat list. If you planning to writing this to file, or sending over TCP you might want to use iolist, which are much easier to create (you could drop append and flatten calls) and faster.