简体   繁体   English

Haskell偶数迭代

[英]Haskell even number iteration

I'm trying to drop all odd number from a list of integers.. however having some problems (I'm a total newbie), here's my code: 我正在尝试从整数列表中删除所有奇数..但是有一些问题(我是一个新手),这是我的代码:

 evenfunc :: [Int] -> [Int]
 evenfunc li =
        x = head li
        y = tail li
        if even x
          then x : myevenfunc xs --take head an pass tail recursively
        else
          drop x li : myevenfunc xs --drop head from list and pass tail recursively

Its giving me a 'parse error on input '='' message when trying to run this. 尝试运行此命令时,它给了我“输入'=”消息时出现解析错误。

What am I doing wrong here? 我在这里做错了什么?

Haskell isn't an imperative language in which you order statements, but you can achieve your method by binding values to identifiers using let : Haskell不是命令语句的命令性语言,但是您可以通过使用let将值绑定到标识符来实现方法:

f :: Int -> Int
f x = let y = x + 5 in y * 3

But even using this your function has a few problems: 但是即使使用此功能,也存在一些问题:

  • your recursive call is wrong (use evenfunc ) 您的递归调用是错误的(使用evenfunc
  • your usage of drop is probably wrong 您对drop的使用可能是错误的
  • you never define xs anywhere 你永远不会在任何地方定义xs

All in all, it is probably best to remodel your approach using library functions. 总而言之,最好是使用库函数来重塑您的方法。 filter does exactly what you want: filter器完全符合您的要求:

evenfunc list = filter even list

Or, even: 甚至:

evenfunc = filter even

Of course the given solution using filter should be preferred, but the recursive version could be instructive, too: 当然,使用filter的给定解决方案应该是首选,但是递归版本也可以提供指导:

evenfunc :: [Int] -> [Int]
evenfunc [] = []
evenfunc (x:xs) = if even x then x : tail else tail where
    tail = evenfunc xs  

The first line evenfunc [] = [] takes care of the base case - the empty list. 第一行evenfunc [] = []处理基本情况-空列表。 You were missing this in your solution, and if you call head on an empty list, you get an exception. 您在您的解决方案中缺少这一点,如果你调用head一个空的列表上,你会得到一个例外。

The second line deconstructs the list using a pattern: x is the head and xs is the tail. 第二行使用一种模式来解构列表: x是头部, xs是尾部。 Then we use if pretty much as in imperative languages, with the difference that it returns a value (so it is in fact closer to the ternary operator x ? y : z in Java etc). 然后我们使用if几乎在命令式语言,用它返回一个值的差值(所以它实际上更接近三元运算符x ? y : z中的Java等)。 In order to avoid repetition, we define a sub-expression tail in the where clause. 为了避免重复,我们在where子句中定义了一个子表达式tail If it is weird to you to use things before you define them, you can use let instead, which works similar. 如果您在定义事物之前先使用它们很奇怪,则可以使用let代替,它的工作原理类似。 Of course, calculating tail means to execute the recursive call. 当然,计算tail意味着要执行递归调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM