我是 Haskell 的新手,我正在尝试应用一个函数(gcd)来输入标准输入,它是行分隔的,每行包含不少于或多于两个数字。这是我的输入示例:
3 10 4 1 100 288 240
I am currently breaking up each line into a tuple of both numbers, but I am having trouble figuring out how to separate these tuples and apply a function to them. Here is what I have so far:
import Data.List
main :: IO ()
main = do
n <- readLn :: IO Int
content <- getContents
let
points = map (\[x, y] -> (x, y)). map (map (read::String->Int)). map words. lines $ content
ans = gcd (fst points :: Int) (snd points :: Int)
print ans
任何作为两个开始寻找此答案的好地方的信息将不胜感激。我已经阅读了 Learning Haskell 教程,但没有找到任何关于这个特定问题的信息。
最佳答案
你很接近。在调用 gcd
之前没有理由转换为元组或元组列表.
main = do
contents <- getContents
print $ map ((\[x,y] -> gcd (read x) (read y)) . words) . lines $ contents
所有有趣的东西都在
print
之间和 contents
. lines
将内容分成几行。 map (...)
将函数应用于每一行。 words
将行拆分为单词。 \[x,y] -> gcd (read x) (read y)
将匹配两个字符串的列表(否则会抛出错误 - 通常不是好的做法,但对于像这样的简单程序来说很好),将这些字符串读取为 Integer
s 并计算它们的 GCD。如果你想利用惰性IO,为了在输入每一行后打印每个结果,你可以改变它如下。
main = do
contents <- getContents
mapM_ (print . (\[x,y] -> gcd (read x) (read y)) . words) . lines $ contents
关于string - Haskell - 尝试将函数应用于多个数字的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29357910/