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

Haskell如何在main函数中打印play_games函数的运行输出结果

解决方案

现有代码问题

  • 你写的return $ play_games lplayer1 lplayer2 numGames score一行在IO的do块中没有实际作用:Haskell里的return不会中断后续代码执行,只是将纯值包装为IO类型,你没有绑定计算结果,运算后的值直接被丢弃了。
  • 末尾打印的score是你最开始定义的初始值(0, 0),不是play_games运行后的计算结果。

修改后的main函数代码

main :: IO ()
main = do 
    let initScore = (0, 0)
    putStrLn "Please input total number of games."
    numGames <- readLn :: IO Int 
    putStrLn "Please input series of numbers for player 1 with no spaces."
    player1  <- readLn :: IO Int
    let lplayer1 =  listT player1 
    putStrLn "Please input series of numbers for player 2 with no spaces." 
    player2 <- readLn :: IO Int 
    let lplayer2 =  listT player2
    -- 绑定计算后的最终得分
    let finalScore = play_games lplayer1 lplayer2 numGames initScore
    print lplayer1
    print lplayer2
    -- 打印初始得分和最终得分,按需调整即可
    putStr "初始得分:"
    print initScore
    putStr "最终得分:"
    print finalScore

补充说明

  • 把原有的无意义return行替换为变量绑定,将play_games的运算结果存储到finalScore变量后直接打印,即可输出你需要的运行结果。
  • 可选优化1:play_games中的length xs > n-1 || length xs < n-1可以简化为length xs /= n-1,运行逻辑完全一致,代码更简洁。
  • 可选优化2:当前代码如果遇到输入的玩家数字长度小于要进行的游戏局数时,会出现模式匹配错误,你可以新增空列表匹配分支处理异常情况,示例如下:
    play_games [] _ _ score = score -- 可自定义异常返回逻辑
    play_games _ [] _ score = score -- 可自定义异常返回逻辑
    

内容的提问来源于stack exchange,提问作者Michael Oladimeji

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:24:07