How do I display a list of long integers? (Mercury language) - mercury

In io.write_list(List(integer), ",", OutputPred, !IO), what is OutputPred? I'm trying to display a list of type integer. The list is initially never empty.

io.write_list(MyList, ",", io.write, !IO), where MyList is a list of type integer, will cause MyList members to be printed/displayed. Each member has the following display format i(1, [integer_value]), so it's an awkward appearing output, but is correct. An empty list prints nothing and doesn't result in error.
An alternative is io.write(MyList, !IO) and produces the same result.
The answer to the question of what OutputPred is is io.write. io.print also works.
This information was obtained from Mercury.org

The following Mercury code will display/print the list of type Integer in a more common form: [10, 9, 8,..., 2, 1].
io.write_string(string.join_list(" ,", map(integer.to_string, My_List)), !IO).
The square brackets have to be added separately and can be obtained with preceding and trailing io.write_string commands.
It works. My_List is a list of elements of type integer.
This information was obtained from Mercury.org

Related

sort values of an orddict

In order to extract the values (records) of an orddict as a sorted list, tried this:
-module(test).
-compile(export_all).
-record(node, {name="", cost=0}).
test() ->
List = orddict:append("A",#node{name="A",cost=1},
orddict:append("B",#node{name="B",cost=2},
orddict:new())),
lists:sort(fun({_,A},{_,B}) -> A#node.cost =< B#node.cost end,
orddict:to_list(List)).
The sort fails with exception error: {badrecord,node}.
What would be the correct syntax?
Solved:
The correct insertion method is orddict:store/2 instead of orddict:append/2. Then the pattern {_,A} matches for the comparison function.
The correct syntax is:
lists:sort(fun({_,[A]},{_,[B]}) -> A#node.cost =< B#node.cost end,
orddict:to_list(List)).
I not found note about this in documentation,but you can look in source code of module.
As #Pascal write in comments the reason is that orddict:append/3 is a function provided to append a value to an existing Key/Value pair where Value must be a list. In the use case, the key doesn't exist, so the pair is created and the Value append to an empty list.
Btw, you always can print and compare real and expected result.
io:format("~p~n",[orddict:to_list(List)])
For your example that is:
[{"A",[{node,"A",1}]},{"B",[{node,"B",2}]}]

Format on Prolog

I have a doubt making tables with format, I need to make tables, I know I can make it this way:
If for example my table is tabla("estudents",["name","age","id"]).
But I have a problem, I need to get the numbers of attributes of the table, then I'll set a length of 18 to each square and the length will be N..
print_table_name(C):- tabla(C,A), //I SEARCH MY TABLE
atom_codes(Name,C), //PASSING THE NAME TO ATOM
length(A,N), //I GET MY NUMBER OF ATRIBUTES
Length is 18*N, //Length WILL BE THE LENGTH OF THE TABLE
print_edge(N), //HERE I PRINT THE TOP EDGE
format('|~t~a~t~N|)|~n',Name), //HERE IS MY ERROR
print_edge(N). //HERE I PRINT THE BOTTOM EDGE
print_edge(0):- format('~n',[]).
print_edge(N):- format('+~`-t~18|+', []), M is N-1, print_edge(M), !.
format('|~t~a~t~N|)|~n',Name) here I can't pass N as a variable, then I dont know how I can do to format get the N, N is the length of the table..
It print this
+--------------------------------------------------------------------------+
|students
||
+--------------------------------------------------------------------------+
and if I put the length where is N, then it works.
+--------------------------------------------------------------------------+
| students |
+--------------------------------------------------------------------------+
The problem is that I don't know how to pass the variable N to format.
In this case you should pass N as an argument to the format/2 predicate. Replace the variable N in the format by the symbol * and put N in the argument list.
I'm not sure if you will get the desire effect, but at least it won't fail.
format('|~t~a~t~*|)|~n',[Name, N]).
Edit
Right now I can only test the solution in this limited online interpreter: I replace the ~t by the character dot ~46t to see the effect and this is the result:
?- format('|~46t~a~46t~*|)|~n',['students', 72]).
|...............................students................................)|
PS: Are you sure about the parenthesis between the two last vertical bar?

How to 'array push' a string into a list in TI-Nspire?

As homework, I must swap letters in a given string. I already figured out how to do this, but not how to display them at once. it involves a for loop. so if I include disp x in the for loop, it displays them between parentheses and a space, but I want them all together, so instead of
"a"
"b"
"c"
I want "abc". Is there a way to do this? Should I push the variable into an array and then display the array after the for loop? How to push variables in to an array?
This is in TI-Nspire CX Cas btw.
To add an element x to an array A use augment(A, {x}).
For your specific case, I would use a string variable (call it string) to which I concatenate the next letter at each iteration of the for loop. So if the next letter to be added is in the variable letter, you would put the following line of code at the end of your for loop: string := string & letter.
here is also way:
Local array
array[dim(array)+1] := value
I would answer you by an example covering your scenario. Let's say we are aiming to have a array listing the elements of binaries when we construct an integer into the base2 (binary).
Define LibPub develope(a,b)=
Func
Local mi,m,q
mi:=mod(a,b)
q:=((a-mi)/(b))
Disp mi
While q≥b
a:=q
m:=mod(a,b)
q:=((a-m)/(b))
Disp m
EndWhile
EndFunc
The above small program develops an integer in decimal base into the binary base; however each binary is shown in a separate line as you mentioned:
ex:
develope(222,2)
0
1
1
1
1
0
1
enter image description here
but this is not what you want, you want is in a single line. IMPORTANCE IS THAT YOU SHOULD LIKELIHOOD WANT EACH ELEMENT BE ACCESSIBLE AS A SEPARATE INTEGER, RIGHT? LIKE AS AN ELEMENT IN A ARRAY LIST, THAT'S WHAT YOU LOOKING FOR RIGHT?
There we Go:
Define LibPub develope(n,b)=
Func
Local q,k,seti,set,valid
valid:=b
If valid>1 Then
q:=n
k:=0
set:={}
While q≠0
seti:=mod(q,b)
q:=int(((q)/(b)))
k:=k+1
seti→set[k]
EndWhile
Else
Disp "Erreur, La base doit être plus grand que 1."
EndIf
Return set
EndFunc
Basically, because we do not know how many elements are going to be added in the array list, the set:={} declares an array with an undefined dim (typically length) in order that dynamically be augmented.
The command seti→set[k] will add the value of the seti whatever it is, into the k position of the array list.
and the return set simply returns the array.
if you need to get access to a specific element, you know how to to that: elementNumber5:=set[5]
I wish it helps.

mathematica: PadRight[] and \[PlusMinus]

Is there any way that
PadRight[a \[PlusMinus] b,2,""]
Returns
{a \[PlusMinus] b,""}
Instead of
a \[PlusMinus] b \[PlusMinus] ""
?
I believe that i need to somehow deactivate the operator properties of [PlusMinus].
Why do i need this?
I'm creating a program to display tables with physical quantities. To me, that means tables with entries like
(value of a) [PlusMinus] (uncertainty of a)
When i have several columns with different heights, i'm stuffing the shorter ones with "", so i can use Transpose the numeric part of the table.
If the column has more than one entrie, there's no problem:
PadRight[{a \[PlusMinus] b,c \[PlusMinus] d},4,""]
gives what i want:
{a \[PlusMinus] b,c \[PlusMinus] d,"",""}
It is when the column has only one entrie that my problem appears.
This is the code that constructs the body stuffed with "":
If[tested[Sbody],1,
body = PadRight[body, {Length[a], Max[Map[Length, body]]
With
tested[a__] :=
If[Length[DeleteDuplicates[Map[Dimensions, {a}]]] != 1, False,
True];
, a function that discovers if is arguments have the same dimension
and
a={Quantity1,Quantity2,...}
Where the quantities are the one's that i want on my table.
Thanks
First you need to be aware of that any expression in Mathematica is in the form of Head[Body]
where body may be empty, a single expression or a sequence of expressions separated by commas
Length operate on expressions, not necessarily lists
so
Length[PlusMinus[a,b]]
returns 2 since the body of the expression contains to expressions (atoms in this case) that are a and b
Read the documentation on PadRight. The second argument define the final length of the expression
so
PadRight[{a,b},4,c] results with a list of length 4 with the last two elements equal to
PadRight[{a,b},2,c] results with the original list since it is already of length 2
Therefore
PadRight[PlusMinus[a,b],2,anything] just returns the same PlusMinus[a,b] unchanged since it is already of length 2
so, youר first example is wrong. You are not able to get a result with head List using PadRight when you try to pad to an expression with head PlusMinus
There is no problem of executing
PadRight[PlusMinus[a,b],3,""]
but the result looks funny (at best) and logically meaningless, but if this is what you wanted in the first place you get it, and following my explanations above you can figure out why
HTH
best
yehuda

itration behaviour when list length = 1

I'm quite new to python and am having issues with for loop behaviour. In my code I'm reading config from a file using configobj. The contents of the config file are variable and that is where I'm seeing issues.
Here's my test code:
if webconf.has_key(group):
scenario_list = webconf[group]['Scenarios']['names']
for scenario in scenario_list:
print "Scenario name = %s\n" % scenario
The "scenario_list" variable will contain any number of strings. When 'names' has multiple elements "scenario" is set to the value of each element, which is fine. When "names" has only 1 element then the loop iterates over each character of the first entry, breaking my code.
So, how do I get the for loop simply to return the value of the entry in "scenario_list" when list length is 1?
Thankyou in advance for any advice offered.
Are you using tuples rather than lists?
aTuple = (1,2,3)
aList = [1,2,3]
The big difference between tuples and lists are that tuples are immutable and lists are mutable. That is, with a list you may change the element of a list, or even add and remove elements.
The problem that you are likely encountering is related to a concept called tuple unpacking.
aList = [0] # aList is now [0]
notATuple = (0) # notATuple is now 0
# there was exactly one element in the tuple, so it was unpacked in the variable
aTuple = (0,) # aTuple is now (0,) - a tuple with one element
# the comma indicates that you wish that the tuple should not be unpacked
The only other problem I think of is that you are not putting the scenario string in a list or tuple when you have only one scenario. Python treats strings like lists (well, more like tuples) of characters. As such, if you iterate over a string you get the individual characters (the behaviour you experienced). Hence, you must put your scenario string in a list (or tuple) if want to iterate over your one string, and not its characters. Had you not been using strings you would have seen a runtime error.

Resources