Answered step by step
Verified Expert Solution
Question
1 Approved Answer
ocaml Add a definition (to functions.ml ) for a function sumsquares : int -> int such that sumsquares n is the sum of the squares
ocaml
Add a definition (to functions.ml ) for a function sumsquares : int -> int such that sumsquares n is the sum of the squares of the integers from o to n, e.g. sumsquares o should evaluate to 0, sumsquares 1 should evaluate to 1, and sumsquares 4 should evaluate to 1 + 4 + 9 + 16 = 30. Now add a definition for a function sumodds such that sumodds n sums only the odd numbers between 1 and n, eg sumodds 1 should evaluate to 1, sumodds 4 should evaluate to 1+3 , and sumodds 8 should evaluate to 1 + 3 + 5 + 7 = 16. Challenge: We can generalize both of these functions to the functions sumf : (int -> int) -> int -> int , which takes a function f : int->int and an int n as arguments, and returns fo + f1 + ... + fn. In the first case, f = (fun n -> n*n) and in the second, f = (fun n -> if n mod 2 = 1 then n else 0) Write a definition for the function sumf. Some test cases include sumf (fun n-> 1) 10 = 11 , sumf (fun n -> 2*n) 5 = 30, and sumf (fun n -> (n land 1)*n) 8 = 16. Write a function countc : string -> char -> int such that countc sc counts the number of times character c appears in the string s. So for example counto "acab" 'a' should evaluate to 2; countc "birdofprey" 'z' should evaluate to 0; and countc "zzzzz" 'z' should evaluate to 5. Hint: you will probably find it useful to define a helper function that counts the number of times c appears between either the beginning of the string and a given index or the end of the string and a given index. Write a function right justify : int -> int -> string such that rightjustify w n returns a string representation of n padded with enough spaces in front so that the string has width w. (If the string representation of n has length greater than w, no padding should be added). So rightjustify 5 123 should evaluate to the string 123" and rightjustify 1 314 should evaluate to the string "314Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started