haskell - 试图用 Haskell 找到 GCD。我的代码中的错误在哪里?
问题描述
作为一个练习,我试图自己写这个,但我被卡住了,不知道我的代码中的错误在哪里。
module Hf where
--sumSquaresTo :: Integer -> Integer
--sumSquaresTo x = sum [ n^2 | n <- [1..x] ]
divides a b = b `mod` a == 0
divisors a = [n | n <- [1..a], n `divides` a ]
lnko :: Integer -> Integer -> Integer
lnko a b = [n | n <- [1..max(a b)], (n `divides` a) && (n `divides` b) ]
GHCI 输出:
error:
* Couldn't match expected type `Integer'
with actual type `[a0 -> a0]'
* In the expression:
[n | n <- [1 .. max (a b)], (n `divides` a) && (n `divides` b)]
In an equation for `lnko':
lnko a b
= [n | n <- [1 .. max (a b)], (n `divides` a) && (n `divides` b)]
|
12 | lnko a b = [n | n <- [1..max(a b)], (n `divides` a) && (n `divides` b) ]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error:
* Couldn't match expected type `Integer -> a0'
with actual type `Integer'
* The function `a' is applied to one argument,
but its type `Integer' has none
In the first argument of `max', namely `(a b)'
In the expression: max (a b)
|
12 | lnko a b = [n | n <- [1..max(a b)], (n `divides` a) && (n `divides` b) ]
| ^^^
error:
* Couldn't match expected type `a0 -> a0'
with actual type `Integer'
* In the second argument of `divides', namely `a'
In the first argument of `(&&)', namely `(n `divides` a)'
In the expression: (n `divides` a) && (n `divides` b)
* Relevant bindings include
n :: a0 -> a0
(bound at C:\\Users\erdos\Desktop\haskell\hazi1.hs:12:17)
|
12 | lnko a b = [n | n <- [1..max(a b)], (n `divides` a) && (n `divides` b) ]
| ^
error:
* Couldn't match expected type `a0 -> a0'
with actual type `Integer'
* In the second argument of `divides', namely `b'
In the second argument of `(&&)', namely `(n `divides` b)'
In the expression: (n `divides` a) && (n `divides` b)
* Relevant bindings include
n :: a0 -> a0
(bound at C:\\Users\erdos\Desktop\haskell\hazi1.hs:12:17)
|
12 | lnko a b = [n | n <- [1..max(a b)], (n `divides` a) && (n `divides` b) ]
| ^
Failed, no modules loaded.
解决方案
嗯,有2个错误。
在 Haskell 中,你不写
max(a b)
,而只是写max a b
. 这称为柯里化。您的函数实际上定位了所有公因数。例如:
λ lnko 8 16 [1,2,4,8]
如果您相应地修改类型签名,它将起作用。或者您可以以某种方式选择其中一个因素。
总的来说,这是很棒的代码。继续前进!
推荐阅读
- python - numpy 作者如何决定是否将函数放入 numpy.* 与 numpy.ndarray.* 中?
- go - 如何在 Visual Studio 代码中允许“供应商”文件夹支持
- html - Css Position:sticky 仅在 MOBILE 中不起作用
- python - 如何从 .gitlab-ci.yml 文件中提取单个管道名称?
- php - 如果脚本被注入到私有页面中,XSS 错误仍然很危险吗?
- python - Pandas 列的字典并选择正确的值
- ansible - ansible 检查文件名与不同的字符串大小写,我可以实现 if/else 吗?
- r - 如何在特定字符串上添加字符?
- c - 我怎样才能弄清楚为什么函数有分段错误
- javascript - "console.error: "带有有效载荷 {"name":"Login"} 的操作 'navigate' 未被任何导航器处理。"