Using Haskell list comprehension get the integral cube

Viewed 138

Given any natural num n, the integral cube root of n is the greatest natural number i such that i3 ≤ n.

As an example, the integral cube root of 9 is 2, since 23 = 8 but 33 = 27. I'm trying to write a function func using list comprehension to get the integral cube root to for any natural number.

I got the list of cubes as cubes = [x ^ 3 | x <- [1..]]

1 Answers

You can work with takeWhile :: (a -> Bool) -> [a] -> [a] to obtain only the elements that are less than or equal to n. For example:

Prelude> takeWhile (\i -> i^3 <= 33) [1..]
[1,2,3]

So we can construct a function to obtain all the integers for which the cube root of n is greater than that number:

cubes :: Integral i => i -> [i]
cubes n = takeWhile (\i -> i^3 <= n) [1..]

then we still need to find the largest natural number. We have to find out the last element. If the input is negative, then there is no such value. We thus might want to return a Maybe i instead. We thus have to implement a safeLast:

safeLast :: [a] -> Maybe a
safeLast … = …

and then we can find the largest cube with:

largestCube :: i -> Maybe i
largestCube n = safeLast (takeWhile (\i -> i*i*i <= n) [1..])

I leave the implementation of safeLast as an exercise.

Related