Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Exercise 5.1
- // Write an F# function countNumOfVowels to count the number of vowels in a given string. The type is:
- open System
- let countNumOfVowels (s:string)=
- let isVowel (c:char) =
- if (c = 'a' || c = 'A') then true
- else if (c = 'e' || c = 'E') then true
- else if (c = 'i' || c = 'I') then true
- else if (c = 'o' || c = 'O') then true
- else if (c = 'u' || c = 'U') then true
- else false
- let mutable count = 0
- for x in s do
- if (isVowel(x)) then count <- count + 1
- count
- printfn "%i" (countNumOfVowels("Higher-order functions can take and return functions of any order"))
- Console.ReadKey() |> ignore
- // Exercise 5.2
- // Define a function primesUpTo n to create a list of prime numbers up to a given
- // number. For instance: primesUpTo 10 results in [2; 3; 5; 7]
- open System
- let primesUpTo (n:int)=
- let isPrime (k:int) =
- let mutable prime = true
- for i in [2..k-1] do
- if k % i = 0 then prime <- false
- prime
- let list = [for i in [2..n] do if isPrime(i) = true then yield i]
- list
- printfn "%A" (primesUpTo(10))
- Console.ReadKey() |> ignore
- // Exercise 5.3
- // Define an F# function pclFib n that, when given a number, returns the nth Fibonacci number.
- open System
- let rec fib (n:int) =
- if n = 1 then 0
- else if n = 2 || n = 3 then 1
- else fib (n - 1) + fib (n - 2)
- printfn "%i" (fib(10))
- Console.ReadKey() |> ignore
- // Exercise 5.4
- // a. Define two F# functions doubleNum x that multiplies x by 2 and sqrNum x that multiplies x by itself.
- open System
- let doubleNum (x) = x * 2
- let sqrNum (x) = x*x
- printfn "Result for double num for %i is %i" 10 (doubleNum(10))
- printfn "Result for sqrare num for %i is %i" 10 (sqrNum(10))
- Console.ReadKey() |> ignore
- // b. Define another F# function pclQuad x that applies the doubleNum function defined above twice.
- open System
- let doubleNum (x) = x * 2
- let pclQuad (x) = (doubleNum(doubleNum(x)))
- printfn "Result for pclQuad for %i is %i" 10 (pclQuad(10))
- Console.ReadKey() |> ignore
- // c. Define another F# function pclFourth x that applies the sqrNum function defined (in a.) above twice.
- open System
- let sqrNum (x) = x*x
- let pclFourth (x) = (sqrNum(sqrNum(x)))
- printfn "Result for pclFourth for %i is %i" 10 (pclFourth(10))
- Console.ReadKey() |> ignore
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement