• 一段haskell代码的重构(一)



    版本一:这个是最初的版本,刚刚学习haskell,存在以下几个问题。
    • 只能在ghci交互环境中运行,然后复制粘贴到文件当中。
    • 随机数的生成有点生硬,因为是从网络上抓下来的代码。
    Haskell语言: Codee#26815
    01 -- file: make_math.hs
    02 -- 出n道两个参数的加减法
    03 -- 使用方法: gs n x y
    04 --              n 表示需要多少道题
    05 --              x 表示最小值
    06 --              y 表示最大值
    07 --       比如 gs 10 100 999 表示出10道 加减法
    08
    09 import System.Random
    10 import System.IO.Unsafe
    11
    12 drawInt :: Int -> Int -> IO Int
    13 drawInt x y = getStdRandom (randomR (x,y))
    14
    15 random_list :: (Eq a, Num a) => a -> Int -> Int -> IO [Int]
    16 random_list 0 _ _ = return []
    17 random_list n x y = do
    18     a <- drawInt x y
    19     rest <- (random_list (n-1) x y)
    20     return (a : rest)
    21
    22
    23
    24
    25 math_practice n x y = zip [1..] $ map trans_formula (mix_list (init_val (n*2) x y) (init_sym n ))
    26     where mix_list [] _ = []
    27           mix_list (x:y:xs) (z:zs) = (x,y,z) : mix_list xs zs
    28           init_val n x y = unsafePerformIO $ random_list n x y
    29           init_sym n = unsafePerformIO $ random_list n 0 1
    30
    31           trans_formula (x,y,z) =
    32                       if z ==0
    33                       then ((add_str x y) , (add_str' x y))
    34                       else ((plus_str x y), (plus_str' x y))
    35           add_str x y = show x ++ " + " ++ show y ++ "= "
    36           add_str' x y = show x ++ " + " ++ show y ++ "=" ++ show (x+y)
    37
    38           plus_str x y = show (max x y) ++ " - " ++ show (min x y) ++ "= "
    39           plus_str' x y = show (max x y) ++ " - " ++ show (min x y) ++ "=" ++ (show (abs (x-y)))
    40
    41 gs n x y = do
    42     mapM_ putStrLn [ show a ++ ". " ++ b| (a,(b,c))<-temp_list]
    43     putStrLn " "
    44     mapM_ putStrLn [ show a ++ ". " ++ c| (a,(b,c))<-temp_list]
    45     where temp_list = math_practice n x y
  • 相关阅读:
    mysql连接的空闲时间超过8小时后 MySQL自动断开该连接解决方案
    WebAPI 用户认证防篡改实现HMAC(二)签名验证 AbsBaseAuthenticationAttribute--转
    Calling a Web API From a .NET Client (C#)
    http状态码有那些?分别代表是什么意思
    html 之表单,div标签等。。。。。。。
    mysql之视图,触发器,事务等。。。
    pymysql模块
    MySQL之IDE工具介绍及数据备份
    mysql老是停止运行该怎么解决
    前端基础之html
  • 原文地址:https://www.cnblogs.com/bailiang/p/2546372.html
Copyright © 2020-2023  润新知