繁体   English   中英

将所有haskell数组值除以其gcd

[英]dividing all haskell array values with their gcd

我有以下代码

reducer :: Row El -> Row El
reducer r = let getGCD l = map (\x y -> gcd x y) l
                gcd' = getGCD r
                f = (\x -> map (\y -> y * gcd') x)
             in (f (r))

为了用其gcd划分数组。

reducer [8,8,12] :: Row Int
-- > [2,2,3]

但是我无法适应reducer :: Row El -> Row El函数类型,因此基本上代码不起作用。

我该如何解决?

多个GCD:

gcd' = foldl gcd 0 :: (Integral b, Foldable t) => t b -> b

然后,您可以用它来除以数组中的所有数字:

div' xs = map (`div` g) xs
  where
    g = gcd' xs

3个或更多数量的GCD必须计算把所有的数字进去。 最简单的方法是递归计算列表尾部的GCD,然后计算该值和头部的GCD。 由于gcd x 0 == x对于任何x,我们可以将基本情况定义为0。(Haskell的gcd实现还定义了gcd 0 0 == 0

getGCD [] = 0
getGCD (x:rest) = gcd x (getGCD rest)

有了列表后,您可以找到列表的GCD,然后每个数字除以GCD。

reducer r = let gcd' = getGCD r
            in map (\x -> div x gcd') r

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM