简体   繁体   English

了解素数生成器

[英]Understanding prime number generator

This site shows a function that generate a list of prime numbers. 该站点显示了一个生成素数列表的函数。

-module(eratosthenes).
-export([prime_numbers/1]).

% Sieve of Eratosthenes algorithm for finding all prime numbers up to N.
% http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

% Generate list of prime numbers up to N.
prime_numbers(N) when is_number(N) ->
prime_numbers(N, generate(N)).

prime_numbers(Max, [H|T]) when H * H =< Max ->
   [H | prime_numbers(Max, [R || R <- T, (R rem H) > 0])];

prime_numbers(_, T) -> T.

% Generate sequence 2..N
generate(N) -> generate(N, 2).

generate(Max, Max) -> [Max];

generate(Max, X) -> [X | generate(Max, X + 1)].

I did not understand the function at: 我在以下位置不了解该功能:

prime_numbers(_, T) -> T.

I did this example using a pen and paper: 我用笔和纸做了这个例子:

prime_numbers(5)

1 - prime_numbers(5, [2,3,4,5])
2 - [2 | prime_numbers(5, [R || R <- [3,4,5], (R rem H) > 0)]
3 - [2 | prime_numbers(5, [3,5])]

prime_numbers(5, [3,5])

H * H =< MAX

3*3 =< 5 (False)

prime_numbers(_, T) -> T.

H = 3
T = 5

prime_numbers(5, [3,5]) = [5]

resp: [2,5]


or prime_numbers(5, [3,5]) = [3|[5]]

To understand this, you must look at the whole function: 要理解这一点,您必须查看整个功能:

prime_numbers(Max, [H|T]) when H * H =< Max ->
   [H | prime_numbers(Max, [R || R <- T, (R rem H) > 0])];
prime_numbers(_, T) -> T.

I have removed a newline since it doesn't really apply in this case. 我删除了一个换行符,因为它在这种情况下实际上并不适用。 The idiom in Erlang is to keep clauses for a function together like this. Erlang的惯用法是将函数的子句保持在一起,就像这样。 Note that this function has two clauses. 请注意,此函数有两个子句。 We pattern match against them [0] . 我们对它们进行模式匹配 [0] So this reads: 因此,内容为:

"Suppose we are given something named Max and a list of at least one element with [H|T] . Deconstruct the list into the head element H and the rest of the list T . Now, this pattern has a when guard so it only applies if H*H =< Max . “假设给我们一个名为Max东西,并用[H|T]列出了至少一个元素。将这个列表解构为head元素H和列表T的其余部分。现在,此模式有一个when守卫,因此它只如果H*H =< Max

If this doesn't match, say if the when guard is wrong or we are given an empty list [] , then we try to match against the next clause, (_, T) . 如果这不匹配,请说出当when警卫错误或给我们一个空列表[] ,我们将尝试与下一个子句(_, T)匹配。 This one always matches and throws away the first parameter ( _ ). 该参数始终匹配并丢弃第一个参数( _ )。 It then matches whatever is in the 2nd parameter and binds it to T . 然后,它匹配第二个参数中的任何内容,并将其绑定到T Then it runs its body." 然后它运行它的身体。”

The key to understanding this is to understand pattern matches. 理解这一点的关键是了解模式匹配。 Once you grasp those, the code should be clear and easy to read. 一旦掌握了这些内容,代码就应该清晰易读。

[0] Look up the concept of pattern matching. [0]查找模式匹配的概念。 It is central to many languages like Prolog, ML, Haskell, Erlang, ... 它是许多语言(例如Prolog,ML,Haskell,Erlang等)的核心。

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

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