High order SML questions

Viewed 61

So, I am trying to create a high order SML function that takes in a number and returns all the functions and returns its factors. I have done questions where I would take a list of values and return the values that are divisible but I never did anything like take a number and make a list out of it. Following the question:

Define a function factorize = fn: int -> int list that takes an integer and returns all its factors in a list. For example, factorize 12 will return [1, 2, 3, 4, 6, 12].

The second one is a tricky one, I couldn't understand how its done so dropping it here. I would appreciate any help I get on this one.

Define a function cfoldl that behaves exactly same as the standard foldl except that the type of the function argument does not take a 2-tuple’ instead, the input function should use the currying notation as is ’a -> ’b -> ’b. Thus, the type of cfoldl should be fn : (’a -> b -> ’b) -> ’b -> ’a list -> ’b. For example, cfoldl (fn a => fn b => a-b) 1 [1,2,3,4]; will return 3.

I made this for the foldl:

fun cfoldl f b [] = b
  | cfoldl f b (x::xs) = cfoldl f (f (x, b)) xs;

Thank you!

1 Answers

factorize = fn: int -> int list that takes an integer and returns all its factors in a list

Here's a recursive function that takes a number and generates a list of numbers from 1 up to that number:

fun upto n =
    let fun go i = if i < n
                   then i :: go (i+1)
                   else []
    in go 1
    end

Could you make a function isFactor x y that is true when x is a factor of y?

If you had such a function, could you modify the above function to make use of it?

a function cfoldl that should use the currying notation as is ’a -> ’b -> ’b

fun cfoldl f b [] = b | cfoldl f b (x::xs) = cfoldl f (f (x, b)) xs;

This is exactly foldl.

fun foldl f e []      = e
  | foldl f e (x::xr) = foldl f (f(x, e)) xr;

Here, f : ('a * 'b) -> 'b because f is being used as f(x, e), so naturally it will assume a tuple. You can change the inferred type of f by using it differently.

Can you think of a way where f : 'a -> 'b -> 'b?

Related