2

假设我们有一个列表,我们只想从列表中取出平方数

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

有什么帮助吗?

4

1 回答 1

4

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

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

squareTriSeries n = filter isSquare (triSeries n)
于 2013-09-28T06:23:03.900 回答