最近在玩haskell,刚好孩子要求出三位数的加减法,所以写了个小程序。
- import System.Random
- import System.IO.Unsafe
- drawInt :: Int -> Int -> IO Int
- drawInt x y = getStdRandom (randomR (x,y))
- random_list :: (Eq a, Num a) => a -> Int -> Int -> IO [Int]
- random_list 0 _ _ = return []
- random_list n x y = do
- a <- drawInt x y
- rest <- (random_list (n-1) x y)
- return (a : rest)
- math_practice n x y = zip [1..] $ map trans_formula (mix_list (init_val (n*2) x y) (init_sym n ))
- where mix_list [] _ = []
- mix_list (x:y:xs) (z:zs) = (x,y,z) : mix_list xs zs
- init_val n x y = unsafePerformIO $ random_list n x y
- init_sym n = unsafePerformIO $ random_list n 0 1
- trans_formula (x,y,z) =
- if z ==0
- then ((add_str x y) , (add_str' x y))
- else ((plus_str x y), (plus_str' x y))
- add_str x y = show x ++ " + " ++ show y ++ "= "
- add_str' x y = show x ++ " + " ++ show y ++ "=" ++ show (x+y)
- plus_str x y = show (max x y) ++ " - " ++ show (min x y) ++ "= "
- plus_str' x y = show (max x y) ++ " - " ++ show (min x y) ++ "=" ++ (show (abs (x-y)))
- gs n x y = do
- mapM_ putStrLn [ show a ++ ". " ++ b| (a,(b,c))<-temp_list]
- putStrLn " "
- mapM_ putStrLn [ show a ++ ". " ++ c| (a,(b,c))<-temp_list]
- where temp_list = math_practice n x y
结果示例:
- ghci>gs 10 100 999
- 1. 797 + 899=
- 2. 711 - 163=
- 3. 132 - 101=
- 4. 270 + 292=
- 5. 895 + 710=
- 6. 805 - 329=
- 7. 489 - 193=
- 8. 796 - 179=
- 9. 651 - 144=
- 10. 491 - 476=
-
- 1. 797 + 899=1696
- 2. 711 - 163=548
- 3. 132 - 101=31
- 4. 270 + 292=562
- 5. 895 + 710=1605
- 6. 805 - 329=476
- 7. 489 - 193=296
- 8. 796 - 179=617
- 9. 651 - 144=507
- 10. 491 - 476=15
阅读(2132) | 评论(0) | 转发(0) |