Haskell euclid算法两个整数的最大公约数

标签 haskell

Write a Haskell program egcd using Euclid's algorithm to to determine the greatest common divisor of two integers

我的程序:

eGCD :: Integer -> Integer -> (Integer, Integer, Integer)
eGCD 0 b = (b, 0, 1)
eGCD a b = let (g, s, t) = eGCD (b 'mod' a) a
       in (g, t - (b 'div' a) * s, s)

但在 WinGHCI 中运行时,出现错误:

 Prelude> :load C:\HaskellProject\egcd.hs

 C:\HaskellProject\egcd.hs:3:36: error:
    ? Syntax error on 'mod'
      Perhaps you intended to use TemplateHaskell or TemplateHaskellQuotes
    ? In the Template Haskell quotation 'mod'
    [1 of 1] Compiling Main             ( C:\HaskellProject\egcd.hs, interpreted )
 Failed, modules loaded: none.

最佳答案

要将函数用作中缀运算符,您需要用 ` 包围它们,而不是 ':

eGCD :: Integer -> Integer -> (Integer, Integer, Integer)
eGCD 0 b = (b, 0, 1)
eGCD a b = let (g, s, t) = eGCD (b `mod` a) a
       in (g, t - (b `div` a) * s, s)

' 用于字 rune 字。

关于Haskell euclid算法两个整数的最大公约数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41779339/

相关文章:

F# 中的 Haskell 列表推导式守卫

haskell - 如何使用 aeson 将 JSON 的非字符串部分保留为字符串?

haskell - 模块,导出另一个模块

haskell - 在 GHC 中链接不同的项目

haskell - 获取Data.Tree中节点的父级(haskell)

Haskell 函数采用可变参数函数作为参数(并返回除该函数之外的其他内容),无需灵活实例,纯 Haskell2010

haskell 。 "Could not deduce (t ~ [t]) from the context (Eq t)"

haskell - Haskell 中的二进制映射

haskell - 通过具有不同数量参数的方程式定义函数

Haskell:玩 TypeFamilies;无法推断出问题