3

我们有一个标准输入,例如:

1 2 3
4 5 6
1 3 2
5 3 2
...

每行正好包含三个数字,对于每一行我们要计算函数值

f :: (Int, Int, Int) -> Int

并打印结果。怎么做?

4

2 回答 2

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">
于 2012-11-01T23:43:08.303 回答
2

一个简单的解决方案:

tuple3 :: [Int] -> (Int,Int,Int)
tuple3 [x,y,z] = (x,y,z)

main = mapM_ print . map (f . tuple3 . map read . words) . lines =<< getContents

我仍然不明白为什么要使用元组作为参数,它会导致丑陋的转换。

于 2012-11-01T23:16:20.937 回答