Haskell - 程序挂起
Haskell - program hangs
我现在正在学习Haskell。由于它是一种纯函数式语言,"everything is a value",我相信我可以计算任何我想要的东西,因为 "everything is a value"!
但是,考虑以下程序,该程序尝试在给定用户输入 n 的情况下找到满足条件 a^n + b^n == c^n 的最小整数元组 (a, b, c),这是 a正整数:
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
当我输入 2 时,程序输出期望值 (3, 4, 5),但是,当我输入 3 时,程序似乎永远挂起。我的程序有什么问题?
你的程序没有问题。它似乎永远挂起,因为它确实永远挂起,因为找不到这样的三元组。
我现在正在学习Haskell。由于它是一种纯函数式语言,"everything is a value",我相信我可以计算任何我想要的东西,因为 "everything is a value"!
但是,考虑以下程序,该程序尝试在给定用户输入 n 的情况下找到满足条件 a^n + b^n == c^n 的最小整数元组 (a, b, c),这是 a正整数:
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
当我输入 2 时,程序输出期望值 (3, 4, 5),但是,当我输入 3 时,程序似乎永远挂起。我的程序有什么问题?
你的程序没有问题。它似乎永远挂起,因为它确实永远挂起,因为找不到这样的三元组。