GCK / LCM在Haskell中 [英] GCF/LCM in Haskell

查看:166
本文介绍了GCK / LCM在Haskell中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Haskell非常陌生。



有没有简单的方法可以找到 GCF 或者Haskell中的LCM(最小公倍数)?

解决方案

我不确定LCF是什么,但GCF是Haskell的最爱。使用欧几里德算法,你可以真正了解Haskell是如何工作的。 http://en.wikipedia.org/wiki/Euclidean_algorithm 有一个很好的解释算法设置在这里 http://en.literateprograms.org/Euclidean_algorithm_(Haskell)



这种类型的递归在Haskell中很常见,它显示了语言的表达方式。

  gcd a 0 = a 
gcd ab = gcd b(a`mod` b)

这对参数使用模式匹配来表示任何数字的最大公因式,0是第一个数字。如果数字都是非零的,那么寻找第二个和第一个mod的最大公因子。最终这将在第二个参数中达到0。这将触发第一个模式,并返回第一个参数,这是答案。





函数实际上应该是:

  gcd a 0 = a 
gcd ab = b`seq` gcd b(a` mod` b)其中

这将强制评估以前的递归步骤(a <$ c $如果你是GCDing 1243235452和6095689787662.Seq将参数强制为它的弱头标准形式或者评估最外层的元素,例如c> mod b)数据结构的参数。


I'm extremely new to Haskell.

Is there a simple way to find the GCF or LCM (Least Common Multiple) in Haskell?

解决方案

I'm not sure what the LCF is but the GCF is a Haskell favorite. Using the Euclidean Algroithm you can really get a sense of how Haskell works. http://en.wikipedia.org/wiki/Euclidean_algorithm There is a great explanation of how the algorithm is set up here http://en.literateprograms.org/Euclidean_algorithm_(Haskell) .

This type of recursion is common in Haskell and it shows how expressive the language can be.

gcd a 0 = a
gcd a b = gcd b (a `mod` b)

This uses pattern matching on the arguments to say the greatest common factor of any number and 0 is the first number. If the numbers are both non-zero, then look for the greatest common factor of the second and the first mod the second. Eventually this will reach 0 in the second argument. This will trigger the first pattern and return the first argument which is the answer.

[EDIT]

The function should actually be:

gcd a 0 = a
gcd a b = b `seq` gcd b (a `mod` b) where

This will force the evaluation of the previous recursion step's (a mod b) and will prevent a huge thunk being built in memory if, say, you are GCDing 1243235452 and 6095689787662. Seq forces the argument into its "Weak Head Normal Form" or evaluates the outer most data structure of the argument.

这篇关于GCK / LCM在Haskell中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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