Haskell Filter Multiples of 3 from a List to a Sub

2019-09-05 23:19发布

问题:

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.

回答1:

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