[英]Haskell - Trying to apply a function to lines of multiple numbers
我是Haskell的新手,我正在嘗試將一個函數(gcd)應用於標准輸入,這是行分隔的,每行包含不少於或多於兩個數字。 這是我輸入的一個例子:
3 10 4 1 100 288 240
我目前正在將每一行分成兩個數字的元組,但我無法弄清楚如何分離這些元組並將函數應用於它們。 這是我到目前為止:
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
並計算他們的GCD。
如果要使用惰性IO,為了在輸入每一行后打印每個結果,可以按如下方式更改它。
main = do
contents <- getContents
mapM_ (print . (\[x,y] -> gcd (read x) (read y)) . words) . lines $ contents
或者,您可以采用更為迫切的風格:
import Control.Monad
main = do
n <- readLn
replicateM_ n $ do
[x, y] <- (map read . words) `liftM` getLine
print $ gcd x y
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.