我现在正在学习Haskell.因为它是一种纯粹的功能性语言,"一切都是有价值的",我相信我可以计算我想要的任何东西,因为"一切都是有价值的"!
然而,考虑下面的程序,它试图找到满足条件a ^ n + b ^ n == c ^ n的最小整数元组(a,b,c)给定用户输入n,这是一个正整数:
func :: Integer -> (Integer, Integer, Integer)
func n = head $ filter (\(a, b, c) -> a ^ n + b ^ n == c ^ n) listOfTuples
listOfTuplesWith :: Integer -> [(Integer, Integer, Integer)]
listOfTuplesWith 1 = [(1, 1, 1)]
listOfTuplesWith x = [(a, b, x) | a <- [1 .. x - 1], b <- [1 .. x - 1]] ++
[(a, x, b) | a <- [1 .. x - 1], b <- [1 .. x]] ++
[(x, a, b) | a <- [1 .. x], b <- [1 .. x]]
listOfTuples = concatMap listOfTuplesWith [1 .. ]
main = do
line <- getLine
print $ func $ read line
Run Code Online (Sandbox Code Playgroud)
当我键入2时,程序输出预期值(3,4,5),但是,当我键入3时,程序似乎永远挂起.我的计划有什么问题?
你的程序没有任何问题.它似乎永远挂起,因为它确实永远挂起,因为没有这样的三重奏可以找到.