Haskell刷新变量值

时间:2013-11-07 15:18:05

标签: haskell recursion

每次我对函数进行递归时,我想刷新一个变量值。为了简单起见,我将举一个例子。

假设我们给一个函数一个数字(n),它将返回它可以拥有的最大mod,数字本身就更小。

{- Examples:
  n=5 `mod` 5
  n=5 `mod` 4
  n=5 `mod` 3
  n=5 `mod` 2
  n=5 `mod` 1
-}

example :: Integer -> Integer
example n
    |  n `mod` ...  >  !The biggest `mod` it found so far!  && ... > 0
       = !Then the biggest `mod` so far will change its value.
    |  ... = 0 !The number we divide goes 0 then end! = 0

哪里...... =递归(我认为)

我不知道如何更好地描述它。如果你能帮助我,那就太好了。 :)

1 个答案:

答案 0 :(得分:2)

您可以按照描述编写它:

example :: Integer -> Integer
example n = biggestRemainder (abs n) 0
    where
        biggestRemainder 0 biggestRemainderSoFar = biggestRemainderSoFar
        biggestRemainder divisor biggestRemainderSoFar = biggestRemainder (divisor - 1) newBiggestRemainder
            where
                thisRemainder = n `mod` divisor
                newBiggestRemainder = case thisRemainder > biggestRemainderSoFar of
                    True -> thisRemainder
                    False -> biggestRemainderSoFar

此功能也可以更轻松地编写为

example2 :: Integer -> Integer
example2 0 = 0
example2 n = maximum $ map (n `mod`) [1..(abs n)]