首页 > 解决方案 > 试图用 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.

标签: haskellgreatest-common-divisor

解决方案


嗯,有2个错误。

  1. 在 Haskell 中,你不写max(a b),而只是写max a b. 这称为柯里化

  2. 您的函数实际上定位了所有公因数。例如:

    λ lnko 8 16
    [1,2,4,8]
    

    如果您相应地修改类型签名,它将起作用。或者您可以以某种方式选择其中一个因素。

总的来说,这是很棒的代码。继续前进!


推荐阅读