Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1691316
  • 博文数量: 410
  • 博客积分: 9563
  • 博客等级: 中将
  • 技术积分: 4517
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-03 19:59
个人简介

文章分类

全部博文(410)

文章存档

2017年(6)

2016年(1)

2015年(3)

2014年(4)

2013年(32)

2012年(45)

2011年(179)

2010年(140)

分类: LINUX

2012-05-13 00:17:37

最近在玩haskell,刚好孩子要求出三位数的加减法,所以写了个小程序。

  1. import System.Random
  2. import System.IO.Unsafe

  3. drawInt :: Int -> Int -> IO Int
  4. drawInt x y = getStdRandom (randomR (x,y))

  5. random_list :: (Eq a, Num a) => a -> Int -> Int -> IO [Int]
  6. random_list 0 _ _ = return []
  7. random_list n x y = do
  8.     a <- drawInt x y
  9.     rest <- (random_list (n-1) x y)
  10.     return (a : rest)




  11. math_practice n x y = zip [1..] $ map trans_formula (mix_list (init_val (n*2) x y) (init_sym n ))
  12.     where mix_list [] _ = []
  13.             mix_list (x:y:xs) (z:zs) = (x,y,z) : mix_list xs zs
  14.             init_val n x y = unsafePerformIO $ random_list n x y
  15.             init_sym n = unsafePerformIO $ random_list n 0 1

  16.             trans_formula (x,y,z) =
  17.                         if z ==0
  18.                         then ((add_str x y) , (add_str' x y))
  19.                         else ((plus_str x y), (plus_str' x y))
  20.             add_str x y = show x ++ " + " ++ show y ++ "= "
  21.             add_str' x y = show x ++ " + " ++ show y ++ "=" ++ show (x+y)

  22.             plus_str x y = show (max x y) ++ " - " ++ show (min x y) ++ "= "
  23.             plus_str' x y = show (max x y) ++ " - " ++ show (min x y) ++ "=" ++ (show (abs (x-y)))

  24. gs n x y = do
  25.     mapM_ putStrLn [ show a ++ ". " ++ b| (a,(b,c))<-temp_list]
  26.     putStrLn " "
  27.     mapM_ putStrLn [ show a ++ ". " ++ c| (a,(b,c))<-temp_list]
  28.     where temp_list = math_practice n x y
结果示例:

  1. ghci>gs 10 100 999
  2. 1. 797 + 899=
  3. 2. 711 - 163=
  4. 3. 132 - 101=
  5. 4. 270 + 292=
  6. 5. 895 + 710=
  7. 6. 805 - 329=
  8. 7. 489 - 193=
  9. 8. 796 - 179=
  10. 9. 651 - 144=
  11. 10. 491 - 476=

  12. 1. 797 + 899=1696
  13. 2. 711 - 163=548
  14. 3. 132 - 101=31
  15. 4. 270 + 292=562
  16. 5. 895 + 710=1605
  17. 6. 805 - 329=476
  18. 7. 489 - 193=296
  19. 8. 796 - 179=617
  20. 9. 651 - 144=507
  21. 10. 491 - 476=15



阅读(2063) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~