2013-12-18 35 views
2

我需要一些帮助。它应该包含一个整数列表的所有元素,并返回一个Float列表,其中包括3个变体:1)递归,2)列表推导,3)更高阶的函数。我已经写了第一个,它工作得很好:Haskell sqrt - 将整数列表转换为浮点数

-- 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

请注意,你不需要(也不应该使用!)括号在'sqrt x:sqrtL1 ns'中。原则上这仍然是正确的,但只是没有很好的标准Haskell风格。 – leftaroundabout

回答

2

sqrtL2的问题是x不在范围以外的列表理解。你需要做的fromIntegral列表理解这样的内部:

sqrtL2 ns = [sqrt (fromIntegral x) | x <- ns] 

sqrtL3是罚款,除非你没有fromIntegral任何地方,sqrtFloating a => a -> a所以它不会与整数工作要做。所以你需要这个:

map (sqrt . fromIntegral) ns 
+2

为了澄清,它应该只是'sqrtL2 ns = [sqrt(fromIntegral x)| x < - ns]'。换句话说,将'(n:ns)'改为'ns'并且删除where子句。 – mhwombat

+0

好点,更新了我的答案。 – asm