如何过滤列表并在haskell中取出正方形数字

时间:2013-09-28 06:06:29

标签: haskell

想象一下,我们有一个列表,我们只想从列表中取出正方形数

isSquare :: Int -> Bool
isSquare n = truncate(sqrt(x)) * truncate(sqrt(x)) == n
         where x = fromIntegral n


squareTriSemi = filter (isSquare) triSeries

这里是triSeries的定义

triSeries 0 = [0]
triSeries n = map triangular $take n $iterate (+1) 1
where triangular x = x * (x + 1) `div` 2

但它没有编译它像这样抱怨

Couldn't match expected type `[Int]' with actual type `Int -> [t0]'
    In the second argument of `filter', namely `triSeries'
    In the expression: filter (isSquare) triSeries
    In an equation for `squareTriSemi':
        squareTriSemi = filter (isSquare) triSeries

任何帮助?

1 个答案:

答案 0 :(得分:4)

您对triSeries的定义需要Int并返回一个列表。也就是说,triSeries本身不是列表,但像triSeries 10这样的表达式是列表。

修复squareTriSemi定义的一种方法是添加一个传递给triSeries的参数:

squareTriSeries n = filter isSquare (triSeries n)