List Haskell-迭代并填充列表
我对哈斯克尔很陌生,到目前为止,这是我发现的最难理解的语言。我在网上找到了一篇过去的论文,我决定尝试在haskell中实现这一点以供实践 我在myFile.txt中有一个整数列表,如下所示:List Haskell-迭代并填充列表,list,loops,haskell,List,Loops,Haskell,我对哈斯克尔很陌生,到目前为止,这是我发现的最难理解的语言。我在网上找到了一篇过去的论文,我决定尝试在haskell中实现这一点以供实践 我在myFile.txt中有一个整数列表,如下所示: 5 3 30 10 120 80 96 95 96 98 98 其中列表中的第一个数字有一个整数,告诉我接下来将进行多少次测试。在这种情况下,后面是5 我试图为每个测试返回一个数字(例如:20)(例如:330),表示特定范围内的总倍数 作为第一次测试的示例,3 30: 我需要找到每个数字的倍数,从2到第一
5
3 30
10 120
80 96
95 96
98 98
其中列表中的第一个数字有一个整数,告诉我接下来将进行多少次测试。在这种情况下,后面是5
我试图为每个测试返回一个数字(例如:20)(例如:330),表示特定范围内的总倍数
作为第一次测试的示例,3 30:
main = do
let myList = []
handle <- openFile "myFile.txt" ReadMode
contents <- hGetContents handle
let singlewords = words contents
myList = f singlewords
printMyVals myList
hClose handle
f :: [String] -> [Integer]
f = map read
printMyVals :: [Integer] -> IO()
printMyVals myList =
print myList
main=do
让myList=[]
句柄IO()
printMyVals myList=
打印myList
在这一点上,我被卡住了
我试图弄清楚如何迭代列表中的值,并使用这些值用它的倍数填充另一个列表,如上所述
这方面有什么帮助吗?这里有几个部分,如果你把它们分解到每一步,每一步都相当简单。其中每行输入为
m
和n
:
n之间的所有2的倍数
m
和n
之间的m
的所有倍数multiplesOfN n = [n, n+n..]
这将建立一个无限的倍数值列表。Apply
takeWhile(你知道如何阅读和打印,从问题中省略它是有意义的。你能用ghci表达你的问题吗?谢谢你在尝试运行这个函数时提供的信息@Adam Smith,我在运行主函数时得到错误:“multi-st-overflow.hs:(36,3)-(42,46):函数go中的非穷举模式”第36行:转到最后一个值xss@(x:xs)yss@(y:ys)第42行:否则y:go y xss ys知道会出现什么问题吗?@singher您的代码或示例输入必须与给出的不同。请参阅,感谢更新。我确实在代码中出错,我尝试了您的示例,现在可以工作了,但是,里面可能有一个小的逻辑错误。我发现第二个测试,您的代表orts 67 vs当我手动测试它时,我有93个唯一的倍数。我试图找到里面的逻辑错误。@singher给出67的输入是什么?它不包括在测试输入中。输入:10 120-返回值是67
twos = takeWhile (<=30) . multiplesOfN $ 2
threes = takeWhile (<=30) . multiplesOfN $ 3
mergesort :: (Eq a, Ord a) => [a] -> [a] -> [a]
mergesort [] ys = ys
mergesort xs [] = xs
mergesort xss@(x:xs) yss@(y:ys)
| x < y = x : mergesort xs yss
| otherwise = y : mergesort xss ys
-- but this doesn't remove duplicates! Let's deal with that by
-- adding a new argument @lastValue@ and discarding if any match
uniqMergesort :: (Eq a, Ord a) => [a] -> [a] -> [a]
uniqMergesort xs [] = xs
uniqMergesort [] ys = ys
uniqMergesort xss@(x:xs) yss@(y:ys)
| x < y = x : go x xs yss
| otherwise = y : go y xss ys
where
go _ [] [] = []
go lastValue (x:xs) []
| lastValue == x = go lastValue xs []
| otherwise = x : go lastValue xs []
go lastValue [] (y:ys)
| lastValue == y = go lastValue [] ys
| otherwise = y : go lastValue [] ys
go lastValue xss@(x:xs) yss@(y:ys)
| x < y = if x == lastValue
then go lastValue xs yss
else x : go x xs yss
| otherwise = if y == lastValue
then go lastValue xss ys
else y : go y xss ys
main :: IO ()
main = do
handle <- openFile "myFile.txt" ReadMode
contents <- hGetContents handle
let inputs = map (map read . words) . lines $ tail contents
results = [let xs = takeWhile (<=n) . multiplesOfN $ 2
ys = takeWhile (<=n) . multiplesOfN $ m
in uniqMergesort xs ys | [m, n] <- inputs]
mapM_ (print . length) results
hClose handle