Haskell Filter Multiples of 3 from a List to a Sublist

独自空忆成欢 提交于 2019-12-25 04:36:17

问题


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   


来源:https://stackoverflow.com/questions/36578438/haskell-filter-multiples-of-3-from-a-list-to-a-sublist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!