Haskell从列表中过滤3个倍数到子列表 [英] Haskell Filter Multiples of 3 from a List to a Sublist

查看:227
本文介绍了Haskell从列表中过滤3个倍数到子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然试图掌握Haskell和Functional Programming的工作方式,我需要帮助理解为什么我的函数不工作。我正在尝试创建一个函数,它将整数列表作为参数,并从第一个列表中过滤/返回一个包含3的倍数的子列表。这里是我的代码:

 模块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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆