我的程序需要一些帮助。它应该对整数列表中的所有元素进行sqrt并返回一个Float列表,有3种变体:1)递归,2)列表推导,3)高阶函数。我写了第一个,工作得很好:
-- recursive:
sqrtL1 :: [Integer] -> [Float]
sqrtL1 [] = []
sqrtL1 (n:ns) = (sqrt x) : sqrtL1(ns)
where x = fromIntegral n :: Float
-- Listenkomprehension:
sqrtL2 :: [Integer] -> [Float]
sqrtL2 (n:ns) = [sqrt x | x <- ns]
where x = fromIntegral n :: Float --(it doesn't work tho)
-- Higher-order:
sqrtL3 :: [Integer] -> [Float]
sqrtL3 ns = map sqrt ns
但是我在接下来的两个案例中遇到麻烦。有人能帮助我吗?
答案 0 :(得分:2)
sqrtL2
x
的问题不在列表推导范围之外。您需要在列表解析中执行fromIntegral
,如下所示:
sqrtL2 ns = [sqrt (fromIntegral x) | x <- ns]
sqrtL3
很好,除非你的fromIntegral
位于sqrt
,Floating a => a -> a
为map (sqrt . fromIntegral) ns
,因此它不适用于整数。所以你需要这个:
{{1}}