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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/quicmous/article/details/80862842

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

-- 选择菜单。(带副作用的IO编程,和传统编程语言类似。)    
select_action = do
    putStrLn ""
    putStrLn ""
    putStrLn "班级成绩管理系统  主菜单"
    putStrLn "************************"
    putStrLn "*     1. 添加成绩      *"
    putStrLn "*     2. 计算总分      *"
    putStrLn "*     3. 显示成绩      *"
    putStrLn "*     0. 退出          *"
    putStrLn "************************"
    putStr "您选择:"
    action <- getLine
    return action

-- 字符串转整数
toInt x = read x :: Int

-- 输入一个学生成绩
inputStudent = do
    putStrLn "---------------------------------"
    putStr "姓名 = "
    name <- getLine
    if name /= "" then do
        putStr "语文 = "
        yuwen <- getLine

        putStr "英语 = "
        english <- getLine

        putStr "数学 = "
        shuxue <- getLine

        putStr "物理 = "
        wuli <- getLine

        putStr "化学 = "
        huaxue <- getLine
        return [(name, toInt yuwen, toInt english, toInt shuxue, toInt wuli, toInt huaxue, 0)]
    else
        return []

-- 追加学生成绩
appendStudent s = do        
    t <- inputStudent
    if t == [] then return s
    else 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 = do
    mapM print s
    return s

-- 程序主“循环”    
scoreManage s = do
    action <- select_action
    t <- case action of
        "0" -> return s
        "1" -> do
            v <- appendStudent s
            return v
        "2" -> return (calcTotal s)
        "3" -> display s


    if action == "0" then return s
    else do
        w <- scoreManage t
        return w

-- 程序入口
main = scoreManage []

猜你喜欢

转载自blog.csdn.net/quicmous/article/details/80862842