Overload Conflict in SML/NJ - sml

I have the following code to compute the Hofstadter H Sequence, but I am getting an overload conflict error message. I am fairly new to SML therefore i am sure what the error is referring to.
(* Hofstadter H-Sequence *)
fun H(0) = [0]
| H(n) = if n = 0 then [0] else x :: (n - H(H(H(n - 1))));
My goal is to insert the value of each iteration into a list and display it.
Ex: H 10; -->[1, 1, 2, 3, 4, 4, 5, 5, 6, 7]

You're trying to write a function with the type int -> int list.
(It's a good idea to think about the types while writing, even though SML will infer them. A good type system is like autofocus for the mind.)
You can't subtract the result of this function from a number (n - H(...)) since it is a list, nor can you pass a list to to this function – H(H(n - 1)) – since it wants a number.
(And where did the first element, x, come from?)
Start simple, with a function that's just the definition of H(n):
fun H 0 = 0
| H n = n - H(H(H(n-1)))
Test:
- H 0;
val it = 0 : int
- H 1;
val it = 1 : int
- H 2;
val it = 1 : int
- H 4;
val it = 3 : int
Then use that to build a list incrementally.
This variant uses a locally defined helper function that uses the current index and a counter:
fun H_seq n = let fun H_seq' m e =
if m < e
then (H m) :: (H_seq' (m+1) e)
else []
in
H_seq' 0 n
end;
Example:
- H_seq 10;
val it = [0,1,1,2,3,4,4,5,5,6] : int list
This is pretty inefficient, but fixing that is part of the more advanced course...

Related

Use '->' in prolog

I want to generate a list that is made up by sublists which contains 2 intergers and their sum and product.
The expected result is
A = [[2,3,5,6],[2,4,6,8],[2,5,7,10],[2,6,8,12],
[2,7,9,14],[2,8,10,16],[3,4,7,12],[3,5,8,15],
[3,6,9,18],[3,7,10,21],[4,5,9,20]].
But I kept have some sublists that does not have the sum and product:
?- get(A).
A = [[2,3,5,6],[2,4,6,8],[2,5,7,10],[2,6,8,12],
[2,7,9,14],[2,8,10,16],[2,_G419,_G422,_G425],
[3,4,7,12],[3,5,8,15],[3,6,9,18],[3,7,10,21],
[3,_G530,_G533,_G536],[4,5,9,20]].
Here is my code :
get(4,5,[]):-!.
get(N,M,[[N,Q,S,P]|List]):-
Q is M + 1,
S is N + Q,
S =< 10 ->
P is N * Q,
get(N,Q,List);
X is N + 1,
get(X,X,List).
get(List):-get(2,2,List).
I think the problem is about using -> in my code, but I don't know how to fix it, I think the logic about -> is right: if S=<10, then calculate the product and the other value with N and Q; else calculate N+1 and N+2 and ...
The operator precedence of (->)/2 is higher than the
operator precedence of (,)/2. As a result the (,)/2
are grouped together as an argument for (->)/2.
So your rule:
get(N,M,[[N,Q,S,P]|List]):-
Q is M + 1,
S is N + Q,
S =< 10 ->
P is N * Q,
get(N,Q,List);
X is N + 1,
get(X,X,List).
Is basically read by the interpreter as:
get(N,M,[[N,Q,S,P]|List]):-
(Q is M + 1,
S is N + Q,
S =< 10) ->
P is N * Q,
get(N,Q,List);
X is N + 1,
get(X,X,List).
With the result that Q ans S are unbound when
the if condition is not satisfied and the else
part is executed. You can fix your code by introducing
additional parenthesis:
get(N,M,[[N,Q,S,P]|List]):-
Q is M + 1,
S is N + Q,
(S =< 10 ->
P is N * Q,
get(N,Q,List)
; X is N + 1,
get(X,X,List)).
But even with this fix, there is an issue with P
being unbound in the else branch.
For clarity, you might even try a solution without
if-then-else, see for example here
Prolog removing IF THEN ELSE
I concur with Jan, but I want to inteject a point about formatting. Because ; and -> so strongly affect the meaning of a program, it's poor form (meaning makes it harder to understand) to put those operators at the end of a line.
get(N,M,[[N,Q,S,P]|List]):-
Q is M + 1,
S is N + Q,
S =< 10
->
P is N * Q,
get(N,Q,List)
; X is N + 1,
get(X,X,List).
When you arrange code like this it becomes immediately apparent that the entire clause is an if-then-else, with the first 3 lines being the 'if' portion. (Though I wouldn't object to Jan's layout for the final version.)

Range Update - Range Query using Fenwick Tree

http://ayazdzulfikar.blogspot.in/2014/12/penggunaan-fenwick-tree-bit.html?showComment=1434865697025#c5391178275473818224
For example being told that the value of the function or f (i) of the index-i is an i ^ k, for k> = 0 and always stay on this matter. Given query like the following:
Add value array [i], for all a <= i <= b as v Determine the total
array [i] f (i), for each a <= i <= b (remember the previous function
values ​​clarification)
To work on this matter, can be formed into Query (x) = m * g (x) - c,
where g (x) is f (1) + f (2) + ... + f (x).
To accomplish this, we
need to know the values ​​of m and c. For that, we need 2 separate
BIT. Observations below for each update in the form of ab v. To
calculate the value of m, virtually identical to the Range Update -
Point Query. We can get the following observations for each value of
i, which may be:
i <a, m = 0
a <= i <= b, m = v
b <i, m = 0
By using the following observation, it is clear that the Range Update - Point Query can be used on any of the BIT. To calculate the value of c, we need to observe the possibility for each value of i, which may be:
i <a, then c = 0
a <= i <= b, then c = v * g (a - 1)
b <i, c = v * (g (b) - g (a - 1))
Again, we need Range Update - Point Query, but in a different BIT.
Oiya, for a little help, I wrote the value of g (x) for k <= 3 yes: p:
k = 0 -> x
k = 1 -> x * (x + 1) / 2
k = 2 -> x * (x + 1) * (2x + 1) / 6
k = 3 -> (x * (x + 1) / 2) ^ 2
Now, example problem SPOJ - Horrible Queries . This problem is
similar issues that have described, with k = 0. Note also that
sometimes there is a matter that is quite extreme, where the function
is not for one type of k, but it could be some that polynomial shape!
Eg LA - Alien Abduction Again . To work on this problem, the solution
is, for each rank we make its BIT counter m respectively. BIT combined
to clear the counters c it was fine.
How can we used this concept if:
Given an array of integers A1,A2,…AN.
Given x,y: Add 1×2 to Ax, add 2×3 to Ax+1, add 3×4 to Ax+2, add 4×5 to
Ax+3, and so on until Ay.
Then return Sum of the range [Ax,Ay].

Reach A Target number only using other two numbers

I am having two numbers L and R, L means left and R means Right.
I have to get to a certain number(F) using L and R.
Every time i have to start with zero as initial.
Example :
L : 1
R : 2
F : 3
SO minimum number of steps needed to get to F is 3.
Ans : First R, Second R, Third L.
IN this way i need to find the minimum number of ways to do it.
My approach:
Quo = F/R;
Remain : F%R;
x*R-Y*L = Remain
==> (x*R - Remain)/L = Y
this equation is break when (x*R - Remain)%L = 0, so we find x and y from the equation above.
So final Steps would be Quo + x(No. of right steps) + y( no. of left steps).
For Above Example :
Quo = 3/2 = 1;
Remain = 3%2 =1;
Y = (x*2 -1)/1
(x*2 -1)%1 is zero for x=1;
Now increase x from zero,
So x is 1, y is 1
Final Ans = Quo (1) + x (1) + y(1) = 3.
My code :
#include <iostream>
using namespace std;
int main()
{
int F,R,L;
cin >> F;
cin >> R;
cin >> L;
int remain = F%R;
int quo = F/R;
int Right = 0;
int left = 0;
int mode = 1;
while( mode !=0)
{
Right++;
mode = (R*Right - remain)%L;
left = (R*Right - remain)/L;
}
int final = quo + Right + left;
cout << final;
}
But i Don't think it is the good approach as i am putting x in loop which can be pretty costly
Can you please suggest me a good approach to do this question ?
In the given below equation
x*R - Remain = 0modL
where R, L and Remain are fixed.
It can be written as
((x*R)mod L - Remain mod L) mod L = 0
If Remain mod L = 0, then x*R should be multiple of L which makes x to 0modL.
Means x can be 0, nR where n is Integer.
So, simply, you can try x between 0 and L-1 to find x.
So, your loop can run from 0 to L-1 which will keep your loop finite.
Please note that this mod is different from %. -1 mod L = L-1 whereas -1%L = -1
There is another approach.
x*R mod L - Remain mod L = 0 mod L
leads to
x*R mod L = Remain mod L
(x* (R mod L)) mod L = (Remain mod L)
You can compute inverse of R (say Rinv) in field of L (if it does exists) and compute x = (Remain*Rinv)modL.
If inverse does not exists, it means equation cannot be satisfied.
Note: I am not mathematical expert. So, please give your opinion if anything is wrong.
See: https://www.cs.cmu.edu/~adamchik/21-127/lectures/congruences_print.pdf

Why are F# list ranges so much slower than for loops?

I'm surprised how much slower the List range is for the example below. On my machine the for loop is a factor of 8 or so quicker.
Is an actual list of 10,000,000 elements created first? And if so, is there a reason (other than it has not been done yet) why this can't be optimised away by the compiler?
open System
open System.Diagnostics
let timeFunction f v =
let sw = Stopwatch.StartNew()
let result = f v
sw.ElapsedMilliseconds
let length = 10000000
let doSomething n =
(float n) ** 0.1 |> ignore
let listIter n =
[1..length] |> List.iter (fun x -> doSomething (x+n))
let forLoop n =
for x = 1 to length do
doSomething (x+n)
printf "listIter : %d\n" (timeFunction listIter 1) // c50
GC.Collect()
printf "forLoop : %d\n" (timeFunction forLoop 1) // c1000
GC.Collect()
Using ILSpy, listIter looks like this:
public static void listIter(int n)
{
ListModule.Iterate<int>(
new listIter#17(n),
SeqModule.ToList<int>(
Operators.CreateSequence<int>(
Operators.OperatorIntrinsics.RangeInt32(1, 1, 10000000)
)
)
);
}
Here are the basic steps involved:
RangeInt32 creates an IEnumerable (which is inexplicably wrapped by CreateSequence)
SeqModule.ToList builds a list from that sequence
An instance of listIter#17 (your lambda) is new'd up
ListModule.Iterate traverses the list calling the lambda for each element
vs forLoop, which doesn't look much different from what you've written:
public static void forLoop(int n)
{
for (int x = 1; x < 10000001; x++)
{
int num = x + n;
double num2 = Math.Pow((double)num, 0.1);
}
}
...no IEnumerable, lambda (it's automatically inlined), or list creation. There's a potentially significant difference in the amount of work being done.
EDIT
For curiosity's sake, here are FSI timings for list, seq, and for loop versions:
listIter - Real: 00:00:03.889, CPU: 00:00:04.680, GC gen0: 57, gen1: 51, gen2: 6
seqIter - Real: 00:00:01.340, CPU: 00:00:01.341, GC gen0: 0, gen1: 0, gen2: 0
forLoop - Real: 00:00:00.565, CPU: 00:00:00.561, GC gen0: 0, gen1: 0, gen2: 0
and the seq version for reference:
let seqIter n =
{1..length} |> Seq.iter (fun x -> doSomething (x+n))
Using {1..length} |> Seq.iter
is certainly faster as you don't create the full list in memory.
Another slightly faster way than your for loop is:
let reclist n =
let rec downrec x n =
match x with
| 0 -> ()
| x -> doSomething (x+n); downrec (x-1) n
downrec length n
Interesting is that the code for the recursive function boils down to:
while (true)
{
switch (x)
{
case 0:
return;
default:
{
int num = x + n;
double num2 = Math.Pow((double)num, 0.1);
int arg_26_0 = x - 1;
n = n;
x = arg_26_0;
break;
}
}
}
Even when using optimization, there are still a few lines that could have been removed, i.e to this:
while (true)
{
switch (x)
{
case 0:
return;
default:
{
int num = x + n;
double num2 = Math.Pow((double)num, 0.1);
x = x - 1;
break;
}
}
}

What is the Basic Structure of a Function in FORTRAN?

This is something that's I've wanted to know recently, mostly out of curiousity. I'm in the mood to learn some old coding styles, and FORTRAN seems like a good place to start.
I guess I should help you guys out by providing a good starting point.
So how would this C procedure be written in FORTRAN?
int foo ( int x , int y )
{
int tempX = x ;
x += y / 2 ;
y -= tempX * 3 ; // tempX holds x's original value.
return x * y ;
}
I know the entire function could be a single line:
return ( x + ( y / 2 ) ) * ( y - ( x * 3 ) ) ;
But the point of me asking this question is to see how those four statements would be written individually in FORTRAN, not neccessarily combined into a single statement.
Don't blame me - you said old coding styles:
C234567
SUBROUTINE FOO(I,J,K)
C SAVE THE ORIGINAL VALUES
IORIG = I
JORIG = J
C PERFORM THE COMPUTATION
I = I + J/2
J = J - IORIG*3
K = I * J
C RESTORE VALUES
I = IORIG
J = JORIG
END SUBROUTINE FOO
I shudder as I write this, but
all variables are implicitly integers, since they start with letters between I and N
FORTRAN passes by reference, so reset I and J at the end to give the same effect as the original function (i.e. pass-by-value, so x and y were unchanged in the calling routine)
Comments start in column 1, actual statements start in column 7
Please, please, please never write new code like this unless as a joke.
Your function might look like this in Fortran
integer function foo(m, n)
integer i
i = m
m = m + n/2
n = n - i*3
foo = m*n
end function foo
You should be able to get started with any tutorial on Fortran. Some thing like this might help http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/fortran.html
cheers
See Functions and Subroutines:
INTEGER FUNCTION foo(i, j)
...
foo = 42
END
then later:
k = foo(1, 2)
Where do you learn FORTRAN from? Just take a look at the wikibooks!
Derived from the example, I'd say:
function func(x, y) result(r)
integer, intent(in) :: x, y
integer :: r
integer :: tempX
tempX = x
x = x / 2
y = y - tempX * 3
r = x * y
end function foo
Similar to above, but with a main program to illustrate how it would be called.
C2345678
program testfoo
implicit none
integer r, foo
r = foo(4,5)
print *, 'result = ', r
end
integer function foo(x,y)
integer x, y
integer tx, ty
tx = x + y / 2
ty = y - x * 3
foo = tx * ty
return
end
Note that this is Fortran 77, which is what I learned 23 years ago.
True old style in applying the rule IJKLMN for integer
C2345678
FUNCTION IFOO(I,J)
II = I + J/2
JJ = J - I*3
IFOO = II*JJ
END