Haskell - 查找整数的除数 [英] Haskell - Finding Divisors of an Integer

查看:118
本文介绍了Haskell - 查找整数的除数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这本书,这是如何完成的,但我无法得到这个工作。它给我一个错误不在范围内:'ld'。我猜我应该导入一些包,但不知道哪一个。此外,本书在提示中使用GS模块,但我使用的是带有Prelude的WinGHCi。我在这里错过了什么?

  factors:Int  - > [Int] 
因子n | n< 1 =错误不正面
| n == 1 = []
|否则= p:因素(div np)
其中p = ld n

我想这个也可以使用地图和过滤器功能来完成?如何?

解决方案

我想这个任务的目的是教你关于列表解析, filter 和类似的结构,而不是让你编写测试素数的函数或以任何明智的方式创建除数列表。因此,您需要的是谓词 divides

  divides :: Int - > Int  - > Bool 
a`divides` b = ???

然后,将该谓词用于参数 filter 或在列表理解中查找除数列表,并为 isPrime 测试使用除数函数。

According to the book this is how its done, but I am not able to get this to work. It gives me an error Not in scope: 'ld'. I'm guessing I should be importing some package but not sure which one. Also the book uses GS module at the prompt but I'm using WinGHCi that has Prelude. What am I missing here?

factors :: Int -> [Int]
factors n | n < 1 = error "not positive"
          | n == 1 = []
          | otherwise = p : factors (div n p)
                        where p = ld n

I guess this can also be done using map and filter functions? How?

解决方案

I suppose the aim of the assignment is to teach you about list comprehensions, filter and similar constructs, and not to have you write functions that test for primality or create the list of divisors in any sensible way. Therefore what you need is a predicate divides,

divides :: Int -> Int -> Bool
a `divides` b = ???

Then you use that predicate for the argument to filter or in a list comprehension to find the list of divisors, and use the divisors function for your isPrime test.

这篇关于Haskell - 查找整数的除数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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