如何在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

