获取Haskell中已过滤的正+负数的平均值

时间:2016-08-11 21:36:03

标签: haskell

所以我试图接受一个数字列表并返回非负数的平均值减去负数的平均值。

这是我的尝试,我不确定我是否会以完全错误的方式解决这个问题。如果有人能指出我正确的方向,那将不胜感激。

private Sprite sprite;
texture = new Texture(Gdx.files.internal("image.png"));
sprite = new Sprite(texture, 20, 20, 50, 50);
sprite.setPosition(10, 10);
sprite.setRotation(45);
sprite.setCenter(25, 25);
batch.begin();
sprite.draw(batch);
batch.end();

错误

filNeg :: [Int] -> [Int]
filNeg [] = []
filNeg xs = filter (<=0) xs

filPos :: [Int] -> [Int]
filPos [] = []
filPos xs = filter (>0) xs

average :: [Int] -> Int
average [] = []
average x = sum filNeg/length filNeg - sum filPos/length filPos

1 个答案:

答案 0 :(得分:1)

对于第一个错误,average无法在空输入上返回[];它必须返回Int

发生其他两个错误是因为您将filNegfilPos视为列表,而不是返回列表的函数。

average :: [Int] -> Int
average [] = 0
average x = sum (filNeg x) `div` length (filNeg x) - sum (filPos x) `div` length (filPos x)

要将div用作中缀运算符,您需要将其括在反引号中。