2013-12-12 39 views
-2

我想寫在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 

我得老最大的,但我不知道我怎麼能做到這一點。是否有可能從上次函數調用中獲得最大值?

+0

你可以擴展的代碼一點點?我沒有看到這個代碼中應該包含什麼oldRest或者如何使用其餘函數。 – Malcolm

+0

你的代碼沒有意義。你在說'休息'是一些價值和本身的最大值。所以你有一個值的遞歸定義,如果不假設'rest'的某個初始值,那麼這個值是不可能解決的。 – DiegoNolan

+0

我編輯我的問題;) – Cilenco

回答

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 
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