从上次函数调用中获取值

时间:2013-12-12 19:41:04

标签: haskell recursion

我想在Haskell中编写这个方法:

private static int maxSubSumme(int array[])
{
    int maximum  = 0;
    int maxright = 0;

    for(int i=array.length-1; i > -1; i--)
    {
        maxright = Math.max(maxright + array[i], 0);
        maximum = Math.max(maximum, maxright);
    }

    return maximum; 
}

我尝试使用此代码:

maxSubSumme :: [Int] -> Int
maxSubSumme [x] = x
maxSubSumme (x:l) | maxright < maximum = maximum 
                  | maxright > maximum = maxright
                  where 
                      maxright = maxi (x + (maxSubSumme l)) 0
                      maximum  = maxi maximum maxright -- Here is my problem

maxi :: Int -> Int -> Int
maxi x y | x > y     = x
         | otherwise = y

我必须得到旧的最大值,但我不知道如何做到这一点。是否可以从最后一次函数调用中获得最大值?

2 个答案:

答案 0 :(得分:2)

以下是我写这个的方法,你的代码在每个循环上不断更新变量,对我看起来像折叠,

myMax :: Ord a => [a] -> a
myMax (x:xs) = foldl' bigger x xs
  where bigger a x = max a x

或者只是

 myMax :: Ord a => [a] -> a
 myMax = foldl1 max

foldl基本上采用列表x:y:z...,初始元素a和函数f并返回

(((a `f` x) `f` y) `f` z) ...

如果需要显式递归,

 myMax (x:xs) = go x xs
   where go curr (x:xs) = go (max curr x) xs
         go curr  _     = curr

答案 1 :(得分:1)

函数没有显式状态,如果你想携带前一个值,你必须明确地执行它:

myMax [] = error "Empty list"
myMax [x] = x
myMax (x:xs) = go x xs
    where
        go y [] = y
        go y (y1:ys) = if y > y1
            then go y ys
            else go y1 ys