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

如何在Haskell中实现三个列表元素组合的自定义求和字符串输出

How to Get Custom Formatted Sum Output in Haskell

Hey, let's sort this out for you! You can absolutely achieve the formatted output you want—here are a couple of clean approaches, including one that uses the string concatenation pattern you mentioned.

Approach 1: Modify smallTriplets to Generate Formatted Strings Directly

Instead of returning a list of tuples, we'll have the function build the exact string lines you need right in the list comprehension. We'll also keep the let sum = x + y + z binding to avoid recalculating the total:

main = do 
    let smallTriplets xs ys zs = [ "Sum is " ++ show x ++ "+" ++ show y ++ "+" ++ show z ++ " = " ++ show sum
                                 | x <- xs, y <- ys, z <- zs
                                 , let sum = x + y + z
                                 , sum <= 10 ]
    mapM_ putStrLn (smallTriplets [1,2] [3,4] [5,6])

This uses your preferred string concatenation style, and the sum binding keeps the code cleaner and more efficient by reusing the calculated total.

Approach 2: Separate Data Generation from Formatting

If you want to keep the original smallTriplets function (to reuse the tuple data elsewhere), split the logic into two parts—generate valid triplets first, then format them with a helper function:

main = do 
    -- Original triplet generation logic, untouched
    let smallTriplets xs ys zs = [ (x, y, z) | x <- xs, y <- ys, z <- zs, x + y + z <= 10]
        -- Helper to convert a triplet to your desired string format
        formatTriplet (x,y,z) = "Sum is " ++ show x ++ "+" ++ show y ++ "+" ++ show z ++ " = " ++ show (x + y + z)
    -- Print each formatted line
    mapM_ (putStrLn . formatTriplet) (smallTriplets [1,2] [3,4] [5,6])

This is ideal if you need to work with the raw triplet data for other tasks later on.

Both Approaches Produce Your Desired Output:

Sum is 1+3+5 = 9
Sum is 1+3+6 = 10
Sum is 1+4+5 = 10
Sum is 2+3+5 = 10

内容的提问来源于stack exchange,提问作者Ahmad Ismail

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 13:37:31