2017-11-19 1 views
2

Das ist mein Code und ich verstehe nicht, warum ich die Summe nicht machen kann. Zum Beispiel habe ich diese Liste [1; 1; 2; 2; 2; 2; 3; 3; 4; 3; 3; 3] als Eingabe und in out brauche ich [2; 8; 6; 4; 9]. Kann mir jemand bei meinem Problem helfen? Vielen Dank.Ich habe eine Liste von Zahlen. Ich muss die Summe der Ziffern machen, die mit rekursiven Funktionen wiederholt werden

let rec compress l = 
    match l with 
    [] -> [] 
    | [x] -> [x] 
    | x::y::xs when x<>y -> compress(xs) 
    | x::y::xs when x=y -> (x+y)::compress(y::xs) 

Antwort

2

Hier ist eine mögliche Lösung, Rekursion:

let compress l = 
    let rec loop last acc l = 
     match (l, last) with 
     | [], None -> [] 
     | [], Some _ -> [acc] 
     | x::xs, None    -> loop (Some x) acc (x::xs) 
     | x::xs, Some n when x = n -> loop last (n+acc) xs 
     | x::xs, _     -> acc :: loop (Some x) x xs 
    loop None 0 l 

Es verwendet einen Zusatz Parameter acc, die das Ergebnis und last ansammelt, die das vorherige Element darstellt.

2

Hier ist eine weitere mögliche Lösung:

let compress l = 
    if List.isEmpty l then [] 
    else 
     let rec loop (last, acc) xs = 
      let h = List.head acc 
      match xs with 
      | [] -> (last, acc) 
      | y::ys when y = last -> loop (y, (y + h)::List.tail acc) ys 
      | y::ys -> loop (y, y::acc) ys 

     let h = List.head l 
     List.tail l 
     |> loop (h, [h]) 
     |> (snd >> List.rev) 

compress l 
val it : int list = [2; 8; 6; 4; 9] 

Beachten Sie, dass die Loop-Funktion Schwanz rekursiv ist.

Verwandte Themen