How to clear a HashArray in Poly/ML? - sml

Not much methods for that, I found only two methods about that? delete, fold.
so I do:
fold ( fn ( k, _, _ ) => delete ( h, k ) ) () h;
But I don't Think it is a good idea? How to do that smart?

Related

Understanding print at the end of list when removing duplicates

I've been trying to learn Prolog by writing a simple program that given a list of items, returns/stores a copy of the list without duplicates in the same order. Ex: [1,1,2,3,3,3,5] returns [1,2,3,5]. I'm using the append to add the numbers to an empty list and the member to check if the integer already has been added.
remove_duplicates([], R).
remove_duplicates([H|T], R) :-
member(H, R)
-> remove_duplicates(T, R)
; append(H, R),
remove_duplicates(T, R).
I've gotten the code to almost work, however when running the code it returns R = [1, 2, 3, 6|_].
I've tried tracing and debugging however I'm unable to understand why the |_ is added at the end.
My thought process for the code is as following, please point out if I'm misunderstanding something.
remove_duplicates([], R). % If first list is empty, return R. (Used to stop the recursion).
remove_duplicates([H|T], R) :-
member(H, R)
-> remove_duplicates(T, R) % If head is member of R (=true), call remove:_duplicates again without the head.
; append(H, R),
remove_duplicates(T, R). % else (if member(H, R) = false), add the head to list R and call remove_duplicates again with tail and R.
My answer to the question implement a prolog predicate that removes all duplicate elements as noted by #brebs is close, but it will not give you what you want. This
list_set( [] , [] ) .
list_set( [X|Xs] , Ys ) :- memberchk(X,Xs), !, list_set(Xs,Ys) .
list_set( [X|Xs] , [X|Ys] ) :- list_set(Xs,Ys) .
prefers the last of duplicated items, so
[1,2,3,3,2,1]
reduces to
[3,2,1]
Which violates the constraint in your problem statement, that you get
a copy of the list without duplicates in the same order.
We can switch that up to prefer the first of any duplicate elements by using a helper predicate with an accumulator and introducing the use of append/3:
list_set( Xs , Ys ) :- list_set( Xs , [] , Ys ) .
list_set( [] , Ys , Ys ) .
list_set( [X|Xs] , Ts , Ys ) :- memberchk(X,Ts) , ! , list_set(Xs,Ts,Ys) .
list_set( [X|Xs] , Ts , Ys ) :- append(Ts,[X],T1) , list_set(Xs,T1,Ys) .
This is fastest method I've found so far (doesn't use append or reverse):
https://stackoverflow.com/a/74024975/

Multiple scala calls faster than tail recursive custom function

I hope this is the right place for this question.
I wrote some code to improve collision detection on a 2D simulation. Part of this algorithm is to associate a list of objects to the specific 2D area where they belong. A function f: (Seq[Box], Seq[T]) => Map[Box, Seq[T]].
I first implemented it with native Scala functions like map, groupBy, ... but then I needed it to return also Boxes with empty Seq[T] and groupBy doesn't do that, so I wrote a recursive function that in my view should be faster that the previous one (this might be me not knowing a better way but this is not the main question).
It turns out that my tail recursive implementation is computationally slower than the one using Scala libraries, its execution time grows faster than the other (benchmarked). I don't understand why, can someone point me to the reason?
def spreadAcrossFast[T](
nodes: Seq[Box],
objects: Seq[T]
) = {
// I create the pairs (reference box, objects that intersects the box)
// intersects() is called nodes.size * object.size times
val assigned = for (
b ← nodes;
s ← objects if intersects( b, s )
) yield ( b, s )
// Group by Box and clean the format of the association above
assigned
// Should be O(n*Log n)
.groupBy( _._1 )
// Maximum nodes.size iterations
.map { x ⇒
// Can consider objects.size / nodes.size iterations
( x._1, x._2.map( _._2 ) )
}
}
def spreadAcrossSlow[T](
nodes: Seq[Box],
objects: Seq[T],
compact: Boolean = true // If compact == true, don't include in the output Box that
) = { // have empty content
#tailrec
def loop( boxes: Seq[Box], acc: Map[Box, Seq[T]] ): Map[Box, Seq[T]] = boxes match {
// End of the boxes, return the accumulator
case Nil ⇒ acc
// Get the objects that intersect the box and add them to the accumulator
case b +: bs ⇒
// Every call it goes through objects.size items
// intersects() is called nodes.size * object.size times
val objInBox = objects.filter( intersects( b, _ ) )
val newAcc = if ( objInBox.isEmpty && compact ) acc else acc + ( ( b, objInBox ) )
loop( bs, newAcc )
}
// nodes.size iterations
loop( nodes, Map.empty[Box, Seq[T]] )
}
Seq is an instance of List.
From my point of view spreadAcrossFast has more iterations than spreadAcrossSlow and the most expensive operation, intersects(), is called the same number of times, nodes.size * objects.size
UPDATE: No luck even with (but the code is cleaner):
def spreadAcrossSlow[T: SpatialIndexable](
nodes: Seq[Box], objects: Seq[T], compact: Boolean
): Map[Box, Seq[T]] = {
val acc = scala.collection.mutable.HashMap[Box, Seq[T]]()
for ( b ← nodes ) {
val objInBox = objects.filter( intersects( b, _ ) )
if ( objInBox.nonEmpty || !compact ) acc += ( ( b, objInBox ) )
}
acc.toMap
}

OCaml overload numeric literal with Camlp4

I am writing a small script with some combinatorics utilities. When I need a numeric literal like 0 or 1 in a different type, I use _0 and _1, but this solution is less than ideal. Is it possible to use Camlp4 to reinterpret numeric literals within a given context or add a new type of numeric literal with a dedicated suffix?
open Num
let zero = num_of_int 0
let one = num_of_int 1
let _0 = zero
let _1 = one
(* some useful infix operators *)
let ( + ) = ( +/ )
let ( - ) = ( -/ )
let ( * ) = ( */ )
let ( < ) = ( </ )
let ( > ) = ( >/ )
let ( = ) = ( =/ )
let ( / ) numer denom =
if mod_num numer denom = _0
then div_num numer denom
else invalid_arg "division is not a total function"
(* factorial, naive *)
let rec fact n =
if n < _0
then invalid_arg "negative factorial"
else if n = _0
then _1
else
n * fact (n - _1)
(* naive algorithm *)
let choose n k = (fact n / fact k) / fact (n - k)
In short, no. Camlp4 is preprocessor of untyped parse tree. It cannot do such type sensitive thing.
If you would want (and I bet you will not), you can run type checking against the untyped parse trees in Camlp4 and infer the types of your special numerals, then replace them by corresponding values. It is theoretically possible but none has ever tried it, since P4's parse tree is completely different from the one of OCaml.
PPX preprocessor, which is meant to replace Campl4, has some hope, since it handles the same untyped parse tree as OCaml and therefore it is easy to apply OCaml type checker. TyPPX (https://bitbucket.org/camlspotter/typpx) is such a framework to provide APIs for type dependent preprocessing.
You may want to have a look to delimited overloading — it requires to qualify your constants by surrounding the expression e with M.(e) where M is the name of your module (you can define aliases).

Creating the #< BIP in prolog

I'm basically trying to create 'my own' version of the #< operator in prolog, i.e. something to the tune of at_less(F1,F2), where it returns true if F1#
So some example inputs:
?- at_less(1.2,0)
yes
?-at_less(0,1.2)
no
?-at_less(f(1,2,a),f(1,2,b)).
yes
Obviously I don't want to use the #< operator, as that would be redundant :)
I can understand how one would compare two atoms, with something like
%atom_pr(+A1,+A2): A1 #< A2, where A1 and A2 are atoms.
atom_pr(L1,L2):-
atom_codes(L1,First), %atom codes for first
atom_codes(L2,Second),%atom codes for second
code_compare(First,Second). %compare the codes, return true or false
code_compare([HF|TF],[HS|TS]):-
( HF=HS ->
code_compare(TF,TS)
;
HF<HS ->
true
;
fail
).
code_compare([],X):-
true.
code_compare([],[]).
%(I understand this is probably not the most efficient way of going about this, but I'm %just beginning!)
Is there something similar I can do for all constants, rather than just atoms? Is there a command similar to atom_codes/2? If not, the only thing I can think of doing is breaking it into a great number of if -> else statements, checking to see if the first is an atom and the second isn't etc. etc., but this seems like a kinda tedious/poor method perhaps?
Thanks in advance for the help!
Edit: Thanks to the help below, I've gotten a program running that is functional (at least from what I can tell). I've put it in the code below, in case someone else wanders here. I believe it is, however, extremely inefficient, so there's plenty of room for improvement :)
%flat_pr(+F1, +F2): F1#<F2, where F1 and F2 are flat ground terms
flat_pr(F1,F2):-
( compound(F1) -> %these ifs here to check what type F1 and F2 are
( compound(F2) -> %comparing/succeeding/failing as appropriate
compound_compare(F1,F2) %(atom>integer>float>compound)
; % I believe these ifs could definitely be cut down though
( atom(F2) ->
true
;
( float(F2) ->
true
;
( integer(F2) ->
true
)
)
)
)
)
;
( atom(F1) ->
( compound(F2) ->
false
;
( atom(F2) ->
atom_pr(F1,F2)
;
( float(F2) ->
false
;
( integer(F2) ->
false
)
)
)
)
)
;
( float(F1) ->
( compound(F2) ->
false
;
( atom(F2) ->
true
;
( float(F2) ->
number_pr(F1,F2)
;
( integer(F2) ->
true
)
)
)
)
;
fail
)
;
( integer(F1) ->
( compound(F2) ->
false
;
( atom(F2) ->
true
;
( float(F2) ->
false
;
( integer(F2) ->
number_pr(F1,F2)
)
)
)
)
)
.
compound_compare(F1,F2):- %compares compounds (arity first)
functor(F1,N1,A1), %get arity
functor(F2,N2,A2),
( A1<A2 -> %compare arity
true
;
( A1>A2 ->
false
)
;
( A1=A2 -> %if arity the same
F1 =.. L1, %compound -> list
F2 =.. L2,
list_compare(L1,L2) %compare the lists
)
)
.
list_compare([],[]). %base case
list_compare([H|T],[H1|T1]):-
( flat_pr(H,H1) -> %if H#<H1
list_compare(T,T1) %compare Tails
;
false %else false
)
.
atom_pr(L1,L2):-
atom_codes(L1,First), %atom codes for first
atom_codes(L2,Second),%atom codes for second
code_compare(First,Second). %compare the codes, return true or false
number_pr(L1,L2):- %simple number comparison...straight forward
( L1=<L2 ->
true
;
fail
).
code_compare([HF|TF],[HS|TS]):- %just runs through atom codes
( HF=HS ->
code_compare(TF,TS)
;
HF<HS ->
true
;
fail
).
code_compare([],X):-
true.
code_compare([],[]).
I'd love to see ways to improve this though! Cheers
Not sure about BIN-Prolog but in SWI-Prolog atom_codes does the trick:
?- atom_codes('jack\&^',K).
K = [106, 97, 99, 107, 38, 94].
?- atom_codes('17.2345',K).
K = [49, 55, 46, 50, 51, 52, 53].
Update:
If you need to compare terms, 1) freeze them (see further) to make the terms ground and 2) use unif (=..) to transform a term to a list, e.g., f(1,2) becomes [f,1,2], and then for each element: a) if it is an atom or a number, then use atom_codes; b) if it is a term, apply the same procedure recursively.
Freezing ensures that the variables are compared in order of their appearance. By "freezing" I mean the following predicate taken from the classical Sterling and Shapiro's book "The Art of Prolog":
numvars('#VAR'(N),N,N1) :- N1 is N+1.
numvars(Term,N1,N2) :- nonvar(Term), functor(Term,_,N),
numvars(0,N,Term,N1,N2).
numvars(N,N,_,N1,N1).
numvars(I,N,Term,N1,N3) :- I<N, I1 is I+1,
arg(I1,Term,Arg), numvars(Arg,N1,N2),
numvars(I1,N,Term,N2,N3).
frz(A,B) :- frz(A,B,0).
frz(A,B,Min) :- copy_term(A,B), numvars(B,Min,_),!.

returning the max of a list

I am trying to return the max of a list.
I have the following code
list_max([]) ->
[];
list_max([H|T]) ->
list_max(H, T).
list_max(Temp, []) ->
Temp;
list_max(Temp, [H|T]) when H > Temp ->
Temp = H;
list_max(Temp, T).
But am struggling to relate to Erlang.
How do I assign something to temp and replace it to the highest?
Erlang is one of those languages in which I find it easier to show than to explain.
list_max([] ) -> empty;
list_max([H|T]) -> {ok, list_max(H, T)}.
list_max(X, [] ) -> X;
list_max(X, [H|T]) when X < H -> list_max(H, T);
list_max(X, [_|T]) -> list_max(X, T).
and call it thus:
{ok, Max} = list_max(MyList).
Sorry, maybe I'm missing something. Are you looking for:
lists:max(List). %% Find the max in List
How do I assign something to temp and replace it to the highest?
The short answer is that you can't. Variables in Erlang cannot be changed once assigned.
The slightly longer answer is that, while you can't change a variable inside a particular function call, you can always self-recurse. Tail-recursion in Erlang is optimized.
In the example code that you provided, list_max will only ever look at the first two elements of the list. The fourth and fifth clauses should each call list_max again, with the new value of Temp in the first parameter. This is a common thing to do in functional languages. In this case, Temp is known as an Accumulator (I often name the variable Acc to reflect this use, but of course you can name it whatever you want).
Let me show another solution that could be seen as "in between" Macelo's answer and stmi's answer:
list_max( [H|T] ) -> list_max( H , T ).
list_max( X , [] ) -> X;
list_max( X , [H|T] ) -> list_max( erlang:max(H, X) , T ).
(I also ditched the clause that detects the empty list, because I don't think it really buys you much - though it will now throw an exception if you call it with an empty list.)
Erlang is a single assignment so you cannot change "variables". You can only create new ones.
My recommendation is to look at the lists module. Inside lists.erl you will find:
max([H|T]) -> max(T, H).
max([H|T], Max) when H > Max -> max(T, H);
max([_|T], Max) -> max(T, Max);
max([], Max) -> Max.
You don't update the Max variable (Temp in your example), but rather call the function with the new value or return it from the function.
Easy peasy... :-)
You can also express than in built in functions:
-module(list_max).
-compile(export_all).
list_max([]) -> none;
list_max([H | T] = List) ->
lists:foldl(fun erlang:max/2, H, T);
list_max(_) -> badarg.