110k views
1 vote
The following exercises should all have one-line solutions using map, foldr, or foldl. You can also use other predefined functions, but do not write any additional named functions. If you need helper functions, use anonymous ones. For example, if the problem says "write a function add2 that takes an int list and returns the same list with 2 added to every element" your answer should be:

fun add2 x = map (fn a => a+2) x;
1. Write a function il2rl of type int list -> real list that takes a list of integers and returns a list of the same numbers converted to type real. For example, if you evaluate il2rl [1, 2, 3] you should get [1.0, 2.0, 3.0]. Hint: since you are taking a list, applying an action to each item in the list, and getting a list of the same number of elements back in list form --- you should use map.

User SwissMark
by
8.8k points

1 Answer

4 votes

Final answer:

To convert a list of integers to a list of real numbers, use the map function with a fromIntegral lambda function.

Step-by-step explanation:

To convert a list of integers to a list of real numbers in functional programming, you can use the map function. The map function applies a specified function to every element in a list and returns a new list with the transformed elements. In this case, we want to convert each integer to a real number, so we can use a lambda function to accomplish this:

il2rl xs = map (\x -> fromIntegral x) xs

In the above solution, we use the fromIntegral function to convert each integer to a real number. We apply this function to each element of the input list using map. Finally, the result is a new list with real numbers.

To convert a list of integers to a list of real numbers, use the map function with a fromIntegral lambda function.

User Arkonautom
by
8.1k points