let rec prime : int -> bool
= fun n -> let rec f a = if (a = 1) then 1
else if (n mod a) = 0 then 0
else if ((f a-1) = 1) then 1
else 0
in
if ((f n-1) = 1) then true
else false
As you can see from my code, I want to implement a function which can tell given number is prime or not.
I can compile and run this code, but for all X function tell "false".
Why this happens?
Thanks in advance. :)
The expression:
f n-1
is parsed like this:
(f n) - 1
You need to write this:
f (n - 1)
((f n-1) = 1)
f n-1 is equivalent to (f n) - 1, not f (n - 1). So you're taking a number that's either 0 or 1, then subtract 1 from (yielding either -1 or 0) and then seeing whether it's 1, which it can never be.
Note that this wouldn't even have compiled had you made f return a boolean rather than an integer (you can't subtract from a boolean).
Related
Hello I am learning the OCaml language and working on an assignment.
infinite precision natural numbers can be represented as lists of ints between 0 and 9
Write a function that takes an integer and represents it with a list of integers between 0 and 9 where the head
of the list holds the least significant digit and the very last element of the list represents the most significant digit.
If the input is negative return None. We provide you with some use cases:
For example:
toDec 1234 = Some [4; 3; 2; 1]
toDec 0 = Some []
toDec -1234 = None
I have written below code for it.
let rec toDec i =
(
if i < 10 then i::[]
else toDec ((i mod 10)::acc) (i/10) in toDec [] i;
);;
I am getting syntax error on line 4. Since I am new to this language, not able to get what's wrong. Can somebody please help on this.
The in keyword must go with a let. You could use a local function aux, as follows:
let toDec i =
let rec aux acc i =
if i < 10 then i::[]
else aux ((i mod 10)::acc) (i/10)
in
aux [] i
This doesn't do what you want but syntax and types are valid and I'm sure you can fix the rest.
Vicky, you forgot to define acc and also forgot to put else if statement.
Update your code as below,
let rec toDec ?acc:(acc=[]) i =
if i < 0 then None
else if i = 0 then Some acc
else toDec ~acc:((i mod 10)::acc) (i / 10)
Having trouble writing a power function inStandard Ml. Im trying to write a function called exp of type int -> int -> int.
The application exp b e, for non-negative e, should return b^e.
For example, exp 3 2 should return 9. exp must be implemented with the function compound provided below. exp should not directly calls itself. Here is the compound function, it takes in a value n, a function, and a value x. All it does is it applies the function to the value x n number of times.
fun compound 0 f x = x
| compound n f x = compound (n-1) f (f x);
Im having trouble figuring out how to write this function without recursion, and with the restraint of having to use a function that only can use a function with one parameter. Anyone have any ideas of where to start with this?
This is what I have:
fun exp b 0 = 1
| exp b e = (compound e (fn x => x*x) b)
I know that this doesn't work, since if i put in 2^5 it will do:
2*2, 4*4, 16*16 etc.
You are extremely close. Your definition of exp compounds fn x => x*x which (as you noticed) is not what you want, because it is repeatedly squaring the input. Instead, you want to do repeated multiplication by the base. That is, fn x => b*x.
Next, you can actually remove the special case of e = 0 by relying upon the fact that compound "does the right thing" when asked to apply a function 0 times.
fun exp b e = compound e (fn x => b*x) 1
You could just do this instead I believe
fun exp 0 0 = 1
| exp b 0 = 1
| exp b e = (compound (e - 1) (fn x => b * x ) b);
this may not be exactly 100% proper code. I sort of just now read a bit of Standard ML documentation and took some code and reworked it for your example but the general idea is the same for most programming languages.
fun foo (num, power) =
let
val counter = ref power
val total = 1
in
while !counter > 0 do (
total := !total * num
counter := !counter - 1
)
end;
To be more clear with some pseudo-code:
input x, pow
total = 1
loop from 1 to pow
total = total * x
end loop
return total
This doesn't handle negative exponents but it should get you started.
It basically is a simple algorithm of what exponents truly are: repeated multiplication.
2^4 = 1*2*2*2*2 //The 1 is implicit
2^0 = 1
This is a homework. OCaml seems to be made by a psychopath.
let prime : int -> bool
= fun n ->
if n > 2 then
let a = n - 1 in
let rec divisor n a =
if a > 1 && n mod a = 0 then false
else if a = 2 && n mod a <> 0 then true
else divisor n a-1 ;;
else if n = 2 then true
else if n = 1 then false
I am not good at coding and I know that my isPrime algorithm is wrong.
But I wonder where in my code is the mistake that produces the syntax error.
Also is there any way to define the isPrime function in a recursive form?
Example:
let rec prime n = ~
You'll get better responses from experts if you don't gratuitously insult their language :-) But I'm an easygoing guy, so I'll take a stab at your syntax error.
There are quite a few problems in this code. Here are 3 that I see right off:
The symbol ;; is used to tell the interpreter that you've entered a full expression that you want it to evaluate. It's definitely out of place in the middle of a function declaration.
Your second let doesn't have an associated in. Every let must have an in after it. The only exception is for defining values at the top level of a module (like your prime function).
The expression divisor n a-1 is parsed as (divisor n a) - 1. You want parentheses like this: divisor a (n - 1).
In OCaml how would I write a median function that takes 5 arguments and returns the median. For example med5 2 5 7 4 3 would return 4.
I managed to write a med3 function (returns the median of 3 arguments) using if and else statements but this would be ridiculously complex if I attempted the same technique for 5 arguments :(
let med3 a b c =
if ((b<=a && c>=a) || (c<=a && b>=a)) then a
else if ((a<=b && c>=b) || (c<=b && a>=b)) then b else c;;
For the med5 function, I would like to be able to use the min and max functions (built in to OCaml) to discard the highest and lowest values from the set of 5 arguments. Then I could use the med3 function that I have already written to return the median of the remaining 3 arguments, but how do I discard the minimum and maximum arguments!?!?!?!?
Any help would be much appreciated :)
If you can use Array, then just put your 5 entries in an array, sort it, and return a[2]. If it's also forbidden in your assignment, you can use a poor-man's bubble sort to select the max, then the min:
let med5 a b c d e =
(* move the max towards 'e' *)
let a,b = if a<=b then a,b else b,a in
let b,c = if b<=c then b,c else c,b in
...
(* then move the min towards 'd', don't forget to reverse the comparisons *)
...
in med3 a b c
You could put those 5 arguments into a list, then removing an element from a list is easy.
If lists and arrays are forbidden, you can have three variables storing the three greatest elements among the five:
let med5 a b c d e =
let first = ref min_int in
let second = ref min_int in
let third = ref min_int in
if a >= !first then (third := !second; second := !first; first := a)
else if a >= !second then (third := !second; second := a)
else if a >= !third then (third := a);
if b >= !first then (third := !second; second := !first; first := b)
else if b >= !second then (third := !second; second := b)
else if b >= !third then (third := b);
(* you guess what to do for c, d, e ;-) *)
(* return the third largest element: *)
!third
Im doing a homework problem to make a function sumOdd to computer the sum of the first n odd integers, but i cant seem to find any sort of elseif type statement to do so. What im trying to do is below but of course doesnt work:
fun sumOdd n = if n=0 then 0 elseif (n mod 2)=0 then sumOdd(n-1) elseif n + sumOdd(n-1);
Your function didn't compile because elseif is not a keyword in SML. Changing the last elseif to else and other elseif to else if should fix the error.
Furthermore, the function is more readable in the below format:
fun sumOdd n = if n = 0 then 0
else if n mod 2 = 0 then sumOdd(n-1)
else n + sumOdd(n-1)
You could also remove the need for the else if expression by separating the base case from the general case:
fun sumOdd 0 = 0
| sumOdd n = if n mod 2 = 0 then sumOdd(n-1)
else n + sumOdd(n-1)
You should also note that this solution does (and your own) does not actually sum the first N odd numbers. It computes the sum of all odd numbers less than N.
sumOdd(5) gives 9(5+3+1) when it should give 25(1+3+5+7+9).