如何实现givenRange函数以统计列表中指定闭区间内的整数个数?
givenRange in Haskell: Count Elements in a Numeric Range Got it, let's break down how to solve this problem. We need to write a Haskell function givenRange :: Int -> Int -> [Int] -> Int that counts how many elements in the list xs fall between low and hi (including both endpoints).
First, let's restate the requirements clearly with the provided examples:
givenRange 2 4 [1,2,3,4,5] == 3(matches the elements 2, 3, 4)givenRange 5 7 [1,2,3] == 0(no elements fall within the specified range)
Method 1: Use filter + length (Idiomatic Haskell)
This is the most concise and idiomatic approach, leveraging Haskell's standard library functions. We filter the list to keep only elements in the range, then count those elements with length.
givenRange :: Int -> Int -> [Int] -> Int givenRange low hi xs = length $ filter (\x -> x >= low && x <= hi) xs
For a more readable point-free style (omitting the explicit xs parameter), we can extract the range check into a helper function:
givenRange :: Int -> Int -> [Int] -> Int givenRange low hi = length . filter inRange where inRange x = x >= low && x <= hi
Method 2: Recursive Implementation (For Learning Basics)
If you want to understand the underlying recursion instead of relying on library functions, here's a manual recursive solution:
givenRange :: Int -> Int -> [Int] -> Int givenRange _ _ [] = 0 -- Base case: empty list has zero elements in range givenRange low hi (x:xs) | x >= low && x <= hi = 1 + givenRange low hi xs -- Count this element and recurse | otherwise = givenRange low hi xs -- Skip the element and recurse
How it works:
- The base case handles empty lists: there's nothing to count, so return 0.
- For non-empty lists, we check if the first element is in the range. If yes, we add 1 to the result of recursing on the rest of the list. If not, we just recurse on the rest of the list.
Method 3: List Comprehension
Another clean approach uses list comprehensions to generate a list of elements in the range, then takes its length:
givenRange :: Int -> Int -> [Int] -> Int givenRange low hi xs = length [x | x <- xs, x >= low, x <= hi]
The list comprehension iterates over each element x in xs, only keeping those that satisfy both x >= low and x <= hi. We then count those elements with length.
All three methods will correctly handle the provided examples, along with edge cases like empty lists, single-element lists, or ranges that include all elements in the list.
内容的提问来源于stack exchange,提问作者user9749935

