Haskell入门求助:用列表推导式筛选控制台输入的偶数
Fixing Your Haskell List Comprehension for Even Number Filtering
Hey there! Let's work through the issues in your code and get that even-number filter running smoothly.
Key Problems in Your Current Code
Let's break down [x | x <- [nums], x == even, x <= 50] step by step:
- Incorrect list traversal:
x <- [nums]wraps your input listnumsinto a single-element list (so you're iterating over one item: the entire list itself, not individual integers). You need to writex <- numsto iterate over each element in the input list. - Wrong even-check logic:
x == eventries to compare an integerxto theevenfunction itself—this doesn't make sense!evenis a function that takes an integer and returns a boolean (even :: Integral a => a -> Bool), so you should call it withxas the argument:even x.
Fixed Code (Including Console Input)
Since you mentioned reading an integer list from the console, here's a complete working example:
main :: IO () main = do putStrLn "Enter a list of integers (e.g., [1, 2, 33, 50, 52]):" nums <- readLn :: IO [Int] let filteredEvens = [x | x <- nums, even x, x <= 50] putStrLn "Filtered even numbers (<= 50):" print filteredEvens
How This Works:
- The
mainfunction handles input/output: it prompts the user, reads the input list (we specifyIO [Int]to avoid type ambiguity), then processes it. - The corrected list comprehension:
x <- nums: Iterates over each integer in the input list.even x: Checks if the current integer is even.x <= 50: Ensures the number is 50 or smaller.
- Finally, it prints out the filtered list of even numbers.
Just test it by running the program and entering a valid integer list (like [10, 23, 48, 50, 61])—it should output [10,48,50]!
内容的提问来源于stack exchange,提问作者Hajra Zamir
相关产品推荐
相关产品推荐

