Haskell三角形打印代码改造:支持字符串输入实现居中效果
你的思路存在两处明显偏差:
- 类型不兼容:原代码中
TriangleMaker类型定义的第一个入参是Char类型,你直接传入" *"字符串会直接编译报错,根本无法运行。 - 居中逻辑不匹配:原居中三角形的空格计算逻辑是基于填充内容单字符宽度设计的,换成多字符填充串后,原计算的空格数会导致三角形无法正确居中。
改写方案
1 调整类型定义与三角形生成逻辑
把TriangleMaker的入参类型从Char改为String,同时修改两个三角形生成函数的实现,适配多字符填充,同时修正居中计算逻辑:
-- 类型别名修改为接收字符串作为填充单元 type TriangleMaker = String -> Int -> [String] topLeftTriangle :: TriangleMaker topLeftTriangle fillStr n = [concat $ replicate i fillStr | i <- [1 .. n]] centeredTriangle :: TriangleMaker centeredTriangle fillStr n = let unitLen = length fillStr maxLineLen = n * unitLen -- 保留原逻辑首行空行的效果,i从0开始遍历 in [replicate ((maxLineLen - i * unitLen) `div` 2) ' ' ++ concat (replicate i fillStr) | i <- [0 .. n]]
2 调整调用逻辑
getType函数无需修改,只需要调整trekant中调用triangle的参数即可,和你预期的写法一致:
getType :: IO TriangleMaker getType = do let menu = [topLeftTriangle, centeredTriangle] putStr $ unlines [ "What type of triangle do you want to print? (type 1 and then type the int size)", "1) Top Left", "2) Centered"] line <- getLine return (menu !! ((read line :: Int) - 1)) trekant :: IO() trekant = do triangle <- getType size <- getLine putStr $ unlines $ triangle " *" (read size :: Int)
运行效果验证
传入填充串" *"、尺寸6时,居中三角形输出和你预期的完全一致:
ghci> trekant What type of triangle do you want to print? (type 1 and then type the int size) 1) Top Left 2) Centered 2 6 * * * * * * * * * * * * * * * * * * * * *
内容的提问来源于stack exchange,提问作者Mampenda
相关产品推荐
相关产品推荐

