zoukankan      html  css  js  c++  java
  • 一段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
  • 相关阅读:
    Eclipse 开发过程中利用 JavaRebel 提高效率
    数字转化为大写中文
    网页变灰
    解决QQ截图无法在PS中粘贴
    ORACLE操作表时”资源正忙,需指定nowait"的解锁方法
    网页常用代码
    SQL Server 2000 删除注册的服务器
    GridView 显示序号
    读取Excel数据到DataTable
    清除SVN版本控制
  • 原文地址:https://www.cnblogs.com/bailiang/p/2546372.html
Copyright © 2011-2022 走看看