Can I get some help implementing a function that counts the number of cases?
First of all, I'm sorry to ask you the same question over and over again.
I've been trying to implement the function for more than a week, but I don't get the hang of it.
This is the code I wrote now.
fun count (x,nil) = 0
| count(x,y::ys) =
if x=y*2 then 2
else if x=y*4 then 4
else if x=y*10 then 10
else if x=y*20 then 20
else if x=y*100 then 100
else count(x,ys);
I know it's a very ignorant code. But I've practiced implementing the functions you've answered, and I don't understand how to apply them at all.
This is the code I want implemented in c.
int count(int n, int arr[]) {
int cnt = 0;
int num1 = arr[0];
int num2 = arr[1];
if ((n % num1) == 0) cnt++;
if ((n % num2) == 0) cnt++;
if (((n - num1) % arr[1])==0) cnt++;
return cnt;
}
int main() {
int n;
int arr[30];
int res = 0;
scanf("%d", &n);
scanf("%d %d", &arr[0], &arr[1]);
res = count(n, arr);
printf("%d", res);
}
I would like to implement the number function if I do the same thing as the c code. Can I get some help?
I don't completely follow what the intent of the code is, but a nice trick that might be helpful:
In C, if you find yourself updating a local variable, then in SML you can often accomplish the same thing by rebinding the variable:
C:
int x = 0;
if (condition1) x++;
if (condition2) x++;
...
return x;
SML:
let
val x = 0
val x = if condition1 then x+1 else x
val x = if condition2 then x+1 else x
...
in
x
end
Using this trick it should be easy to translate your C function. I'll let you do the rest.
Just one thing to note. When you write code in this style in SML, you're not actually updating local variables at all. The above SML code is equivalent to this, where we make a new variable each time. It's just a bit more convenient to write in the other style.
let
val x0 = 0
val x1 = if condition1 then x0+1 else x0
val x2 = if condition2 then x1+1 else x1
...
in
x2
end