如何通过构建包含 k 个元素的列表(全部为 n)然后使用函数乘积来计算幂函数

How do I calculate a power function by constructing a list with k elements, all being n, and then using the function product

我用一种方法成功了:

power1 :: Integer -> Integer -> Integer
power1 n k | k < 0 = error "power not defined for negative exponent"
           | otherwise = product (replicate (fromInteger k) n)

但是如何在函数内使用列表推导来做到这一点?我试了几个小时来解决它,但我不太理解它。

power1 :: Integer -> Integer -> Integer
power1 n k=product

这是一种使用列表理解来实现的方法:

power1 n k = product [n | _ <- [1 .. k]]

但是请注意,这种方式和您编写的方式都不是很有效。