在Haskell的新函数中使用过滤列表 [英] Using a filtered list in a new function in haskell
问题描述
所以我不太确定如何正确地表达这句话,但是说我想获取列表中所有奇数的和,我是否有两个函数(sumList和getOddNumbers)并将它们组合成sumOddList或是否存在一种将这两个功能整合到一个函数中的方法?如果没有更好的功能,我该如何将它们准确地组合成sumOddList?
So i'm not too sure how to phrase this properly, but say I wanted to get the sum of all odd numbers in a list, do I have two functions (sumList and getOddNumbers) and combine them into sumOddList or is there a way to put these two together in a single function? If there isnt a better function, how exactly would I combine them into sumOddList?
getOddNumbers :: [Integer] -> [Integer]
getOddNumbers [] = []
getOddNumbers (x:xs)
|odd x = x:getOddNumbers xs
|otherwise = getOddNumbers xs
sumList :: [Integer] -> Integer
sumList list = case list of
[] -> 0
(x:xs) -> x + (sumList xs)
我还问主要是因为在使用CodeWorld输出颜色和形状时,将两个diff函数放在一起是我以前遇到的难题.
I also ask mainly because putting two diff functions together is something I struggled with before, when putting a colour and a shape using CodeWorld to output a shape of that colour.
谢谢
(注意:我已经使用Haskell超过5周了,显然我是一个菜鸟)
(Note: I've been using Haskell for just over 5 weeks now and I'm a total noob clearly)
推荐答案
将输出作为输入传递给(另一个)函数
您基本上想做的是使用将getOddNumbers
的输出用作sumList
函数的 input ,所以我们可以将sumOddList
函数定义为:
Passing output as input to (another) function
Well what you basically want to do is use the output of the getOddNumbers
as input for the sumList
function, so we can define a sumOddList
function as:
sumOddList :: [Integer] -> Integer
sumOddList l = sumList (getOddNumbers l)
这里l
是我们要处理的列表,因此结果是getOddNumbers l
的结果上的函数应用程序(带有sumList
函数).
Here l
is the list we want to process, and the result is thus a function application on the result of getOddNumbers l
(with sumList
the function).
上面的模式很常见:通常我们想先通过函数g
传递数据,然后通过函数f
传递结果. Haskell具有 (.) :: (b -> c) -> (a -> b) -> a -> c
函数,用于链"功能.因此,我们可以将sumList
和getOddNumbers
链接在一起,就像:
The above pattern is quite common: frequently we want to pass data first through a function g
, and the result through a function f
. Haskell has the (.) :: (b -> c) -> (a -> b) -> a -> c
function to "chain" functions. We can thus chain sumList
and getOddNumbers
together like:
sumOddList :: [Integer] -> Integer
sumOddList = (.) sumList getOddNumbers
请注意,此处我们不再使用l
参数.在这里,sumOddList
被定义为管道",其中数据首先传递到getOddNumbers
,然后通过sumList
函数进行后处理".
Notice that we no longer use an l
parameter here. sumOddList
is here defined as a "pipeline" where data is first passed to the getOddNumbers
, and then is "post-processed" by the sumList
function.
(.)
函数也可以用作中缀运算符:
The (.)
function can also be used as an infix operator:
sumOddList :: [Integer] -> Integer
sumOddList = sumList . getOddNumbers
这篇关于在Haskell的新函数中使用过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!