我们有一个标准输入,如:
1 2 3
4 5 6
1 3 2
5 3 2
...
每一行都包含三个数字,我们想要计算每一行的函数值
f :: (Int, Int, Int) -> Int
并打印结果。怎么做?
答案 0 :(得分:3)
我会指出一些有用的功能,可以帮助你完成任务:
readFile :: FilePath -> IO String
lines :: String -> [String]
words :: String -> [String]
print :: (Show a) => a -> IO ()
我建议您开设ghci
个会话,稍微尝试一下这些功能,看看他们做了什么,并尝试以创造性的方式将它们混合在一起。我会给你一个良好的开端:
Prelude> str <- readFile "test.txt"
Prelude> print (length (lines str))
<The number of lines in the file "test.txt">
答案 1 :(得分:2)
一个简单的解决方案:
tuple3 :: [Int] -> (Int,Int,Int)
tuple3 [x,y,z] = (x,y,z)
main = mapM_ print . map (f . tuple3 . map read . words) . lines =<< getContents
我仍然不明白为什么要使用元组作为参数,它会导致丑陋的转换。