scala: generating tuples from a list - list

I have a list val l=List(4,3,2,1), I am trying to generate a list of tuples of the format (4,3), (4,2) and so on.
Here's what I have so far:
for (i1<-0 to l.length-1;i2<-i1+1 to l.length-1) yield (l(i1),l(i2))
The output is : Vector((4,3), (4,2), (4,1), (3,2), (3,1), (2,1))
Two questions:
It generates a Vector, not a List. How are these two different?
Is this the idiomatic scala way of doing this? I am very new to Scala, so it's important to me that I learn right.

On the first part of the question, the for comprehension implementation defines ranges 0 to l.length-1 and i1+1 to l.length-1 as IndexedSeq[Int] hence the yielded type is trait IndexedSeq[(Int, Int)] implemented by final class Vector.
On the second part, your approach is valid, yet consider the following where we do not use indexed references to the lists,
for (List(a,b,_*) <- xs.combinations(2).toList) yield (a,b)
Note that
xs.combinations(2).toList
List(List(4, 3), List(4, 2), List(4, 1), List(3, 2), List(3, 1), List(2, 1))
and so with List(a,b,_*) we pattern-match and extract the first two elements of each nested list (the _* indicates to ignore possible additional elements). Since the iteration is over a list, the for comprehension yields a list of duples.

Related

run length decoding of a list in prolog?

I'm trying to decode a given list for example mydecode([(a,1), (b,2), (c,3), (d,2)],X) should give X = ['a','b','b','c','c','c','d','d']. What is the error in this code?
mydecode([],[]).
mydecode([X|Ys],[X|Zs]) :- \+ is_list(X), mydecode(Ys,Zs).
mydecode([[1,X]|Ys],[X|Zs]) :- mydecode(Ys,Zs).
mydecode([[N,X]|Ys],[X|Zs]) :- N > 1, N1 is N - 1, mydecode([[N1,X]|Ys],Zs).
you are asked to handle a list of 'tuples' of 2 elements, not a list of lists of 2 elements
then, the test in the second clause will always fail
the tuples elements are key and value, but you're 'accessing' them in inverse order.
So, remove the second clause - it's irrelevant, since pattern matching will discard ill formed lists.
Change the [1,X] to (X,1) and similarly other references to tuples, and test your code with the query assigned.

Prolog: Parsing a term for semantic correctness (pattern matching)

I am working on an assignment and I am woefully stuck. I have little experience with prolog and I am learning on the job based on online material and a textbook.
The aim of the assignment is to produce a predicate, parse(), that is able to check that a given argument/term is of the following form, returning true or false as appropriate:
((int,int),[(int,float),(int,float)...])
So an int pair, followed by an n-sized list of (int,float) pairs, with both wrapped up in a tuple.
For example:
( (1, 7), [(1, 0.0), (2, 0.5), (3, 0.7), (4, 0.8), (5, 0.8), (6,
0.25), (7, 0.3)] )
Could anyone point me in the right direction for where to begin on this? I haven't ever done this sort of this in Prolog.
I am not looking for a full coded answer, naturally this is an assignment, but just some direction for how to approach this problem. I have no declarative programming background, so this is an educational exercise.
Thanks!
We can start with the observation that what you show is already a valid Prolog term:
?- T = ( (1, 7), [(1, 0.0), (2, 0.5), (3, 0.7), (4, 0.8), (5, 0.8), (6, 0.25), (7, 0.3)] ) .
T = ((1, 7), [(1, 0.0), (2, 0.5), (3, 0.7), (4, 0.8), (5, 0.8), (6, 0.25), (7, 0.3)]).
So, in such a case, there is no manual parsing necessary. By parsing, we typically mean the conversion of unstructured text, such as plain lists of characters or character codes, to a structured representation.
Prolog automatically rejects terms that are not syntactically valid. So, in your case, if you already have such a term, all it takes is to state what must hold about it so that it satisfies all constraints.
In Prolog, it is often useful to first think about building blocks you may want to use as a useful basis. For example, let us describe an (int,float) term:
integer_float_tuple((I,F)) :- integer(I), float(F).
We can use it as follows:
?- integer_float_tuple((3,4.5)).
true.
Note though:
First, the definition is not a true relation. For example, the most general query ?- integer_float_tuple(T). will fail even though there clearly are solutions!
Second, using terms of the form (A,B) is discouraged, also because (',')/2 is already used for so many other things in Prolog. It would be better to represent such pairs as I-F, using (-)/2 which is commonly used to denote pairs throughout Prolog libraries.
In any case, we can build on this definition with:
good_term((Tuple,Tuples)) :-
Tuple = (A,B),
integer(A), integer(B),
maplist(integer_float_tuple, Tuple).
This states everything that must hold for such terms, and thus lets you validate them although, as noted, not generate them. To generalize such predicates to work in all directions, use your Prolog system's CLP(FD) and CLP(R) constraints. This will give you a definition that is monotonic and satisfies many desirable properties we expect from a logic program.
Further, if you really want to parse your data manually (as opposed to relying on Prolog's built-in notion of structured terms), I have two recommendations:
First, add the following directive to your program:
:- set_prolog_flag(double_quotes, chars).
This lets you conveniently write lists of characters with double quotes.
For example:
?- Cs = "abc".
Cs = [a, b, c].
Such a representation is very convenient for what we do next, which is using Prolog Definite Clause Grammars for parsing such lists of characters.
I won't solve the whole task for you, but I give you a start. We can start by describing what we mean by a digit:
digit(D) --> [D], { char_type(D, digit) }.
We use such a grammar with the phrase/2 interface predicate. For example:
?- phrase(digit(D), "5").
D = '5'.
Building on this definition, let us describe lists of digits:
digits([]) --> [].
digits([D|Ds]) --> digit(D), digits(Ds).
Example query:
?- phrase(digits(Ds), "5235").
Ds = ['5', '2', '3', '5'] ;
false.
Finally, let us combine all this to decsribe an integer:
integer(I) --> digit(D), digits(Ds), { number_chars(I, [D|Ds]) }.
With number_chars/2, we are performing the crucial conversion between characters and actual integers, which you need in your own representation.
Example query:
?- phrase(integer(I), "5235").
I = 5235 ;
false.
Using such building blocks, you can conveniently describe the general outline of such lists of characters by forther grammar elements.
Overall, your eventual grammar may look like:
pattern --> "(", whitespace, "(", integer, ",", integer, ")", ...
Where you need to supply definitions for whitespace//0 and complete the whole description.
See dcg for more information about this approach.
In Prolog we write predicates, not functions, that in the most basic case just qualify the 'trueness' of the relation - conventionally described by the 'name' of the predicate, so called functor - among the arguments.
So, you're writing a relation among 3 arguments:
parse(Needle, Haystack, Found) :-
...
You should write down a further relation, that holds true when Needle matches one of the elements of Haystack. So you have a choice: either a recursive parse/3, where the current element to be matched is made explicit in the head pattern (that is, parse(Needle, [Element|Haystack], Found) :- etc) or use member/2 from library(lists), that on backtracking will iterate elements...

List to List of List with all possible combination

First of all, I cannot remember the name of this repetition of list.
I have a list:
myList = [0, 1, 2]
I want to repeat list of list:
[[0,1,2],[1,2,0],...]
I know that I can do permutations myList
But it won't cover the repeated parts such as [[0,0,0],[1,1,1],[1,1,0],...]
So, my questions are what is the name given for such kind of list.
It is not permutations and it definitely is not combinations
In logic, we call it truth table, I believe.
And is there a builtin function for that in haskell?
GHCi, version 7.10.2: http://www.haskell.org/ghc/ :? for help
Prelude> :m +Control.Monad
Prelude Control.Monad> replicateM 3 [0,1,2]
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2],[0,2,0],[0,2,1],[0,2,2],[1,0,0],[1,0,1],[1,0,2],[1,1,0],[1,1,1],[1,1,2],[1,2,0],[1,2,1],[1,2,2],[2,0,0],[2,0,1],[2,0,2],[2,1,0],[2,1,1],[2,1,2],[2,2,0],[2,2,1],[2,2,2]]
Note that basically, the length of the list of permitted values needs in no way be connected to the length of each list of choices.
with list comprehension
x = [0,1,2]
[[a,b,c] | a<-x, b<-x, c<-x]
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2],[0,2,0],[0,2,1],[0,2,2],
[1,0,0],[1,0,1],[1,0,2],[1,1,0],[1,1,1],[1,1,2],[1,2,0],[1,2,1],[1,2,2],
[2,0,0],[2,0,1],[2,0,2],[2,1,0],[2,1,1],[2,1,2],[2,2,0],[2,2,1],[2,2,2]]

How to add sequential numbers to a list of tuples

I have a question which looks quite simple, but I could not find an acceptable answer as yet. It looks that variations of it have already been asked here several times, but none of the answers was helpful to me.
Here it is:
I have a lists of tuples, as follows:
reflist = [("Author1", 1900, "Some reference"), ("Author2", 1901, "Another reference"), ("Author3", 1902, "Yet another reference")]
What I want is to add a sequential number to each tuple in the list, so that I got:
reflist = [(1, "Author1", 1900, "Some reference"), (2, "Author2", 1901, "Another reference"), (3, "Author3", 1902, "Yet another reference")]
This looks silly and a list comprehension should do the trick, but I cannot discern just how :-(
Thanks in advance for any assistance you can provide.
enumerate() runs over a sequence and generates index, value pairs. You can't merge directly into your tuples - because tuples are immutable, you can't change their length - but one way you could do it is to convert the tuples you have into lists, make the index number a list, concatenate the two lists together, and convert the result to a tuple:
reflist2 = [tuple([index+1] + list(ref)) for index, ref in enumerate(reflist)]
(I've edited it to index+1 because enumerate starts counting from 0)
f = [tuple(list(elem).insert(0, i)) for elem in reflist for in range(len(reflist))]
What this list comprehension does is that it tells for each original entry in reflist, it should convert it to a list, then insert a number in some integer list to the 0 position of the list, then convert that list back into a tuple, and put it all together in a ne wlist.

Does this type definition handle empty lists?

I am answering question seven of Haskell's 99 questions. However, I have come to the point where they define the type
data NestedList a = Elem a | List [NestedList a]
and it, from my understanding, will not handle empty lists (ie. []).
But in their example tests they show
*Main> flatten (List [])
[]
Does this type cover empty lists? If so, why?
If it does not, and is a mistake of the websites, how would one write a nested list type that handles empty lists?
The datatype NestedList a contains either elements of type Elem a, or elements of type List [NestedList a].
The first of these, you already seem to understand. The second one, though, has as its argument a list (the normal sort) of NestedList a's. This can be any list, including []. Thus, List [] is a valid NestedList, as would be List[Elem 5], or List [Elem 5, List [Elem 3, Elem 2] ].