Haskell从列表中过滤3个倍数到子列表 [英] Haskell Filter Multiples of 3 from a List to a Sublist
问题描述
模块Main其中
sublist = []
myFunc :: [Int] - > [Int]
myFunc [] = []
myFunc [t] = do
if t`mod` 3 == 0
then t :sublist
else myFunc []
myFunc(h:t)= do
if h` mod` 3 / = 0
then myFunc t
否则做
h:子列表
myFunc t
这只返回一个包含传递给函数的最后一个值,仍然是sublist = []。感谢您的任何建议,您可以提前给我。
我想你需要先转换到功能风格。 / p>
例如,从列表中获取偶数
pre $ code> >过滤即使[1..10]
[2,4,6,8,10]
<如果没有使用现有的函数,您可以实现相同的功能。
filter'::(a - > Bool) - > ; [a] - > [a]
filter'_ [] = []
filter'condition(x:xs)= if condition x
then x:filter'condition xs
else filter'condition xs
divisibleBy3 n = mod n 3 == 0
现在,您程序可以写成
filter'divisibleBy3 inputList
I am still trying to grasp the way Haskell and Functional Programming works, and I need help understanding why my function is not working. I am trying to create a function that takes a list of integers as a parameter and filters out/returns a sublist which contains any multiples of 3 from the first list. Here is my code:
module Main where
sublist = []
myFunc :: [Int] -> [Int]
myFunc [] = []
myFunc [t] = do
if t `mod` 3 == 0
then t : sublist
else myFunc []
myFunc (h:t) = do
if h `mod` 3 /= 0
then myFunc t
else do
h : sublist
myFunc t
This only returns a list containing the last value passed to the function, and still sublist = []. Thanks for any advice you can give me in advance.
I think you need to first switch over mentally to functional style.
for example, this is to get even numbers from a list
> filter even [1..10]
[2,4,6,8,10]
without using the existing functions you can implement the same functionality
filter' :: (a -> Bool) -> [a] -> [a]
filter' _ [] = []
filter' condition (x:xs) = if condition x
then x : filter' condition xs
else filter' condition xs
divisibleBy3 n = mod n 3 == 0
now, your program can be written as
filter' divisibleBy3 inputList
这篇关于Haskell从列表中过滤3个倍数到子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!