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

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 list nums into a single-element list (so you're iterating over one item: the entire list itself, not individual integers). You need to write x <- nums to iterate over each element in the input list.
  • Wrong even-check logic: x == even tries to compare an integer x to the even function itself—this doesn't make sense! even is a function that takes an integer and returns a boolean (even :: Integral a => a -> Bool), so you should call it with x as 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:

  1. The main function handles input/output: it prompts the user, reads the input list (we specify IO [Int] to avoid type ambiguity), then processes it.
  2. 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.
  3. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:28:26