Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Write a function in F# that accepts 3 parameters and counts the number of values in a

specified range (low to high) which are divisible by a third parameter.

 Example:count 1 12 3 would resolve to 4 because there are 4 values from 1 to 12 which


are dividable by 3.
let count lowValue highValue divideValue : int =
// declare local variable that holds the count value
let mutable divisibleNumbers = 0
// iterating through the values
for index in lowValue .. highValue do
// if the index value is divided by the divident
if (index%divideValue)=0 then
// increment the divisibleNumbers values
divisibleNumbers <- divisibleNumbers + 1
divisibleNumbers
// calling the count function with respective values
let totalNum = count 1 12 3
// printing the count value
printfn "%d " totalNum
Write a function in F# that counts the number of values in a list which are divisible by 2.

 Example:count [1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12] 3 would resolve to 4 because there


are 4 values in the list which are dividable by 3.
let count i = Seq.filter i >> Seq.length

let nums = [1;2;3;4;5;6;7;8;9;10;11;12]


let c = nums |> count(fun n -> n%3=0)
printfn "%d" c

Rewrite each of the above so that they accept a "Predicate function" which can be used to
determine whether an item should be counted or not.

 Example: count 1 12 (fun x -> x % 2 = 0) would resolve to 4


 (yes, "=" is used for both testing equality and assignment.)
let rec count l f =
match l with
| [] -> 0
| x::xs -> if(f x) // Predicate Test
then (1 + count xs f)
else (count xs f)

You might also like