如何定义F#函数dependingOnPastValues:基于历史值生成新序列
Alright, let's work through implementing this dependingOnPastValues function in F#. Here's a solution that handles both finite and infinite input sequences correctly, following the rules you laid out:
let dependingOnPastValues (count:int) (fn : int list -> int) (input:seq<int>) : seq<int> = // Maintain a sliding window of the most recent 'count' input values let stateSequence = input |> Seq.scan (fun history newValue -> // Add the new value to the history and keep only the last 'count' elements (history @ [newValue]) |> List.takeLast count ) [] // Initial state: empty history // Pair each input element with the history that existed before processing it Seq.zip stateSequence input |> Seq.map (fun (history, _) -> // Pad the history with leading zeros to reach length 'count' let neededZeros = count - history.Length let fullHistory = List.replicate neededZeros 0 @ history // Apply the transformation function to the full history fn fullHistory )
How this works:
Let's break down the logic with an example to make it concrete. Suppose we use:
count = 3fn = List.sum(sums the history values)input = seq {1; 2; 3; 4}
State tracking with
Seq.scan:
ThestateSequencestarts with an empty list ([]) and builds a sliding window of recent inputs:- After processing 1:
[1] - After processing 2:
[1; 2] - After processing 3:
[1; 2; 3] - After processing 4:
[2; 3; 4]
- After processing 1:
Pairing inputs with pre-processing history:
Seq.zip stateSequence inputmatches each input element to the history that existed before we processed that input:- Input
1→ history[] - Input
2→ history[1] - Input
3→ history[1; 2] - Input
4→ history[1; 2; 3]
- Input
Padding zeros and applying the function:
For each paired history, we add leading zeros to reach the requiredcountlength, then run the transformation function:[]→[0; 0; 0]→ sum = 0[1]→[0; 0; 1]→ sum = 1[1; 2]→[0; 1; 2]→ sum = 3[1; 2; 3]→[1; 2; 3]→ sum = 6
The final output sequence is seq {0; 1; 3; 6}, which aligns perfectly with the requirement to use past values (with leading zeros for missing history) to generate each result.
This implementation is lazy-evaluated, so it works seamlessly with infinite input sequences without blocking or excessive memory usage.
内容的提问来源于stack exchange,提问作者Keneth

