Okay, here's an F# function that takes two lists, xs and ys, representing the x and y coordinates of points, and returns a list of points (x, y) that are local minima or local maxima.
This function defines a local extremum for point (x_i, y_i) as follows:
A local minimum if y_i <= y_{i-1} and y_i <= y_{i+1}.
A local maximum if y_i >= y_{i-1} and y_i >= y_{i+1}.
For the first point, it's compared only to the second point.
For the last point, it's compared only to the second-to-last point.
Points in a flat segment (e.g., ..., 5, 5, 5, ...) will often be considered both local minimums and local maximums relative to their immediate neighbors.
Lists with 0 or 1 points have no local extrema by this definition.
fsharp
module LocalExtrema
/// <summary>
/// Finds local minima and maxima in a sequence of points defined by lists of x and y values.
/// </summary>
/// <param name="xs">A list of x-coordinates.</param>
/// <param name="ys">A list of corresponding y-coordinates.</param>
/// <returns>A list of (x, y) tuples representing the local minima and maxima.</returns>
/// <remarks>
/// A point (x_i, y_i) is a local extremum if y_i is less than or equal to (for minimum)
/// or greater than or equal to (for maximum) its immediate neighbors' y-values.
/// Edge points (first and last) are compared only to their single neighbor.
/// Returns an empty list if input lists are empty, have different lengths, or contain only one point.
/// </remarks>
let findLocalExtrema (xs: list<float>) (ys: list<float>) : list<float * float> =
// Input validation
if List.length xs <> List.length ys then
// Mismatched lengths mean the points aren't well-defined.
// Return empty list as a safe way to handle this, or you could failwith
System.Diagnostics.Debug.WriteLine("Warning: Input lists xs and ys have different lengths.") // Optional warning
[]
elif List.length xs <= 1 then
// 0 or 1 points cannot have local extrema as there are no neighbors for comparison
[]
else
// Combine lists into an array of points for easier indexed access
let pointsArray = List.zip xs ys |> List.toArray
let n = pointsArray.Length // Number of points
// Use Array.mapi to iterate with index and value, checking neighbor values
pointsArray
|> Array.mapi (fun i (x, y) ->
let isLocalMin =
if i = 0 then // First point (compare with next)
y <= pointsArray.[i+1].snd
elif i = n - 1 then // Last point (compare with previous)
y <= pointsArray.[n-2].snd
else // Middle points (compare with previous and next)
let prevY = pointsArray.[i-1].snd
let nextY = pointsArray.[i+1].snd
y <= prevY && y <= nextY
let isLocalMax =
if i = 0 then // First point (compare with next)
y >= pointsArray.[i+1].snd
elif i = n - 1 then // Last point (compare with previous)
y >= pointsArray.[n-2].snd
else // Middle points (compare with previous and next)
let prevY = pointsArray.[i-1].snd
let nextY = pointsArray.[i+1].snd
y >= prevY && y >= nextY
// If it's either a local minimum or a local maximum, keep the point
if isLocalMin || isLocalMax then Some (x, y) else None
)
// Array.choose filters out all None values and unwraps the Some values
|> Array.choose id
// Convert the resulting array back to a list
|> Array.toList
// --- Example Usage ---
let xValues = [1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0; 9.0; 10.0]
let yValues = [10.0; 5.0; 8.0; 2.0; 15.0; 15.0; 15.0; 7.0; 12.0; 1.0]
let localExtrema = findLocalExtrema xValues yValues
printfn "X values: %A" xValues
printfn "Y values: %A" yValues
printfn "Found local extrema (minima and maxima): %A" localExtrema
// Example with a flat section and edge cases
let xValues2 = [1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0]
let yValues2 = [5.0; 3.0; 3.0; 3.0; 8.0; 1.0; 10.0]
let localExtrema2 = findLocalExtrema xValues2 yValues2
printfn "\n--- Second Example ---"
printfn "X values: %A" xValues2
printfn "Y values: %A" yValues2
printfn "Found local extrema (minima and maxima): %A" localExtrema2
// Example with mismatched lengths
let xValues3 = [1.0; 2.0; 3.0]
let yValues3 = [10.0; 5.0]
let localExtrema3 = findLocalExtrema xValues3 yValues3
printfn "\n--- Third Example (Mismatched Lengths) ---"
printfn "X values: %A" xValues3
printfn "Y values: %A" yValues3
printfn "Found local extrema: %A" localExtrema3 // Should print []
// Example with single point
let xValues4 = [1.0]
let yValues4 = [10.0]
let localExtrema4 = findLocalExtrema xValues4 yValues4
printfn "\n--- Fourth Example (Single Point) ---"
printfn "X values: %A" xValues4
printfn "Y values: %A" yValues4
printfn "Found local extrema: %A" localExtrema4 // Should print []
Explanation:
Input Validation: It first checks if the lengths of xs and ys are the same and if the list has at least two points. If not, it returns an empty list.
Combine and Convert:List.zip xs ys creates a list of (x, y) tuples. This list is then converted to an array pointsArray using List.toArray for efficient indexed access, which is needed to compare a point with its neighbors.
Iterate with Index:Array.mapi is used to iterate through the pointsArray. For each element, it provides both the index i and the value (x, y).
Check for Local Extrema: Inside the mapi function, the code checks if the current point (x, y) is a local minimum or a local maximum based on its index i:
If i is 0 (the first point), it's compared only to the next point (pointsArray.[i+1]).
If i is n - 1 (the last point), it's compared only to the previous point (pointsArray.[n-2]).
Otherwise (for middle points), it's compared to both the previous (pointsArray.[i-1]) and the next (pointsArray.[i+1]) points.
The comparison uses >= and <= for non-strict extrema (meaning flat sections can contain extrema).
Collect Extrema: If the point satisfies either the local minimum or local maximum condition (isLocalMin || isLocalMax), it's wrapped in Some (x, y); otherwise, None is returned.
Filter and Unwrap:Array.choose id processes the resulting array of option types. It discards all None values and extracts the value from each Some.
Convert Back to List:Array.toList converts the final array of extrema points back into a list, which is the function's return type.