解释这个输出素数流的haskell代码块 [英] Explain this chunk of haskell code that outputs a stream of primes

查看:84
本文介绍了解释这个输出素数流的haskell代码块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解这段代码:

  let 
sieve(p:xs)= p:筛(筛选(\ x - > x`mod` p / = 0)xs)筛中的
[2 ..]

有人可以为我分解吗?我知道这里面有递归,但那就是我无法理解这个例子中的递归如何工作的问题。

它实际上非常优雅。



首先,我们定义一个函数 sieve ,它包含一系列元素:

sieve(p:xs)

sieve 的主体中,我们将列表的头部(因为我们传递了无限列表 [2 ..] ,2定义为素数),并将其附加到应用 sieve 的结果中的列表:

p:sieve(filter(\ x - > x'mod 'p / = 0)xs)

让我们看一下代码,的列表:

sieve(filter(\ x - > x'mod'p / = 0)xs)

我们将 sieve 应用于过滤列表。让我们来分析一下过滤器的功能:


$ b

  filter(\ x  - > x' mod'p / = 0)xs 

过滤器接受一个函数和一个我们应用该函数的列表,并保留满足该函数给出的条件的元素。在这种情况下,过滤器需要一个匿名函数:

\ x - > x'mod'p / = 0

这个匿名函数有一个参数 X 。它检查 x p 模数(列表的头部,每次 sieve 被调用): $ b

  x 'mod'p 

如果模数不等于0:

 'mod'p / = 0 

然后元素 x 保存在列表中。如果它等于0,则它被过滤掉。这是有道理的:如果 x 可被 p 整除,< x 可以被1以及其本身整除,因此它不是素数。


I have trouble understanding this chunk of code:

let
  sieve (p:xs) = p : sieve (filter (\ x -> x `mod` p /= 0) xs)
in sieve [2 .. ]

Can someone break it down for me? I understand there is recursion in it, but thats the problem I can't understand how the recursion in this example works.

解决方案

It's actually pretty elegant.

First, we define a function sieve that takes a list of elements:

sieve (p:xs)

In the body of sieve, we take the head of the list (because we're passing the infinite list [2..], and 2 is defined to be prime) and append it to the result of applying sieve to the rest of the list:

p : sieve (filter (\ x -> x 'mod' p /= 0) xs)

So let's look at the code that does the work on the rest of the list:

sieve (filter (\ x -> x 'mod' p /= 0) xs)

We're applying sieve to a filtered list. Let's break down what the filter part does:

filter (\ x -> x 'mod' p /= 0) xs

filter takes a function and a list on which we apply that function, and retains elements that meet the criteria given by the function. In this case, filter takes an anonymous function:

\ x -> x 'mod' p /= 0

This anonymous function takes one argument, x. It checks the modulus of x against p (the head of the list, every time sieve is called):

 x 'mod' p

If the modulus is not equal to 0:

 'mod' p /= 0

Then the element x is kept in the list. If it is equal to 0, it's filtered out. This makes sense: if x is divisible by p, than x is divisible by more than just 1 and itself, and thus it is not prime.

这篇关于解释这个输出素数流的haskell代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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