简体   繁体   English

Haskell:这个方法做了什么

[英]Haskell: what does this method do

In my test-exam a question was, what this method does. 在我的考试中,一个问题是,这个方法做了什么。

dos a = ([x | x <- [2..div a 2], mod ax == 0] == [])

I am new to Haskell but as far as I can say, it checks if the result of dos a = ([x | x <- [2..div a 2], mod ax == 0]) is an empty list. 我是Haskell的新手,但据我所知,它检查dos a = ([x | x <- [2..div a 2], mod ax == 0])是否为空列表。 Also x are all numbers of a divided by 2 which have %number == 0. Thus this are all even numbers? 也可为x是的所有数目a由2具有数%== 0,因此这是所有偶数分割? It seems like it checks if the number is dividable through 2, if yes -> false, else otherwise. 它似乎检查数字是否可以通过2分割,如果是 - >假,否则。 Could anyone explain to me the semantic in detail? 任何人都可以向我详细解释语义吗?

You are close to what is going on. 你接近正在发生的事情。 There are several components to understand. 有几个组件需要了解。

First, [2 .. div a 2] generates a list of numbers from 2 to floor(a / 2) . 首先, [2 .. div a 2]生成从2到floor(a / 2)的数字列表。

Next, mod ax == 0 filters out the values from 2 to floor(a / 2) which divide a (eg it finds all the factors of a ). 接着, mod ax == 0过滤出从2值到floor(a / 2)其划分a (例如它找到的所有因素a )。 Thus, the list generated by 因此,生成的列表

[x | x <- [2 .. div a 2], mod a x == 0]

contains all the numbers that divide a . 包含除以a所有数字。

Finally, the == [] checks that this list is empty (eg a has no factors). 最后, == []检查此列表是否为空(例如, a没有因素)。 So, what this function actually does is to determine whether or not a number is prime by attempting to generate its factors, which is easy to see when you use dos as the predicate for filter: 所以,这个函数实际上做的是通过尝试生成其因子来确定数字是否为素数,当您使用dos作为过滤器的谓词时很容易看到:

Prelude> let dos a = ([x | x <- [2..div a 2], mod a x == 0] == [])
Prelude> :t dos
dos :: Integral t => t -> Bool
Prelude> filter dos [2 .. 100]
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] -- Prime goodness

It is the basic algorithm to check if a number is prime or not. 它是检查数字是否为素数的基本算法。 It traverses over all the numbers from 2 to a/2 and checks if any of it divides a , if the list is empty then it means it has no factors between 2 and a/2 which implies the number is prime. 它遍历从2a/2所有数字并检查其中是否有任何一个除以a ,如果列表为空则表示它没有2a/2之间的因子,这意味着数字是素数。

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

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