一段haskell代码的重构(一)

本文介绍了一段使用Haskell语言编写的代码,用于生成加减法练习题。通过输入参数,可以自定义题目数量、数值范围,并以格式化的字符串形式输出题目。代码包括了随机数生成、题目格式化和打印等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


版本一:这个是最初的版本,刚刚学习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

转载于:https://www.cnblogs.com/bailiang/archive/2012/06/12/2546372.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值