You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何定义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 = 3
  • fn = List.sum (sums the history values)
  • input = seq {1; 2; 3; 4}
  1. State tracking with Seq.scan:
    The stateSequence starts 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]
  2. Pairing inputs with pre-processing history:
    Seq.zip stateSequence input matches 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]
  3. Padding zeros and applying the function:
    For each paired history, we add leading zeros to reach the required count length, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:52:39