当前位置: 代码迷 >> 综合 >> Haskell 学习笔记-16:一个简单的应用程序
  详细解决方案

Haskell 学习笔记-16:一个简单的应用程序

热度:21   发布时间:2023-12-12 16:26:56.0

如果不考虑运行速度,感觉函数式编程还是很方便的。发现可以用 read 函数实现字符串转数字,当然也可以转成其他类型。

-- 选择菜单。(带副作用的IO编程,和传统编程语言类似。) 
select_action = doputStrLn ""putStrLn ""putStrLn "班级成绩管理系统 主菜单"putStrLn "************************"putStrLn "* 1. 添加成绩 *"putStrLn "* 2. 计算总分 *"putStrLn "* 3. 显示成绩 *"putStrLn "* 0. 退出 *"putStrLn "************************"putStr "您选择:"action <- getLinereturn action-- 字符串转整数
toInt x = read x :: Int-- 输入一个学生成绩
inputStudent = doputStrLn "---------------------------------"putStr "姓名 = "name <- getLineif name /= "" then doputStr "语文 = "yuwen <- getLineputStr "英语 = "english <- getLineputStr "数学 = "shuxue <- getLineputStr "物理 = "wuli <- getLineputStr "化学 = "huaxue <- getLinereturn [(name, toInt yuwen, toInt english, toInt shuxue, toInt wuli, toInt huaxue, 0)]elsereturn []-- 追加学生成绩
appendStudent s = do        t <- inputStudentif t == [] then return selse do appendStudent (s ++ t)-- 计算一个学生的总分
total (n,a,b,c,d,e,t) = (n,a,b,c,d,e,a+b+c+d+e)-- 计算全班学生总分
calcTotal [] = []
calcTotal (x:xs) = total x : calcTotal xs-- 显示班级成绩
display s = domapM print sreturn s-- 程序主“循环” 
scoreManage s = doaction <- select_actiont <- case action of"0" -> return s"1" -> dov <- appendStudent sreturn v"2" -> return (calcTotal s)"3" -> display sif action == "0" then return selse dow <- scoreManage treturn w-- 程序入口
main = scoreManage []
  相关解决方案