【发布时间】:2023-03-21 09:35:02
【问题描述】:
我对 Haskell 很陌生,我认为要掌握编写 Haskell 程序的窍门,我可能会解决一些项目的欧拉问题。
所以我继续它并实现了 Project Euler 的第 4 个问题。
问题陈述:
回文数的两种读法相同。由两个 2 位数乘积构成的最大回文数是 9009 = 91 × 99。
找出由两个 3 位数乘积构成的最大回文数。
但我的解决方案似乎有问题。
这里是:
projectEuler4 :: (Ord a,Num a) => a
projectEuler4 = max palindromeList
where palindromeList = [reverse(x*y)|x<-[1..999],y <- [1..999]]
GHCI 给我这个错误:
ProjectEuler4.hs:2:17:
Could not deduce (a ~ ([[a0]] -> [[a0]]))
from the context (Ord a, Num a)
bound by the type signature for
projectEuler4 :: (Ord a, Num a) => a
at ProjectEuler4.hs:1:18-35
`a' is a rigid type variable bound by
the type signature for projectEuler4 :: (Ord a, Num a) => a
at ProjectEuler4.hs:1:18
In the return type of a call of `max'
Probable cause: `max' is applied to too few arguments
In the expression: max palindromeList
In an equation for `projectEuler4':
projectEuler4
= max palindromeList
where
palindromeList
= [reverse (x * y) | x <- [1 .. 1000], y <- [1 .. 1000]]
我不知道这意味着什么,并且因为找不到错误原因而感到沮丧。 任何帮助将不胜感激。谢谢。
所以在阅读了一些答案和cmets之后, 我做了这样的事情:
projectEuler4 :: (Ord a,Num a) => a
projectEuler4 = max' palindromeList
where palindromeList = [reverse(show(x*y))|x<-[1..999],y <- [1..999]]
max' :: (Ord a) => [a] -> a
max' [] = error "Empty List"
max' [p] = p
max' (p:ps) = max p (max' ps)
还是不行。
好的..
按照@bheklilr 的建议,我改变了我的程序:
products :: [Integer] -> [Integer] -> [Integer]
products ns ms = [x * y | x <- ns, y <- ms]
isPalindrome :: Integer -> Bool
isPalindrome n = let s = show n in s == reverse s
palindromes :: [Integer]
palindromes = maximum filter (isPalindrome "") (products [100..999] [100..999])
现在我用什么代替引号?我很困惑。
【问题讨论】:
-
这可能与您编写
max(palindromeList)的方式有关。试试max palindromList,不带括号。 Haskell 不使用 C 风格的调用约定。 -
@Eric 这两个表达式是等价的。括号用于分组,写
(((5))) + 4:) -
那么类型类有什么问题吗?
-
你需要一个 Haskell 教程才能开始。
max适用于两个数字,而不是列表(尽管也适用于列表)。您可以使用 GHCi:t max或使用 Hoogle 找到此类信息。 -
@WillNess 我认为函数和参数之间没有空格会导致问题,但我认为没有。今天我学会了……
标签: haskell