Haskell:统计字符串列表中回文数量的函数错误修复咨询
countPalindromes Function in Haskell Let's break down what's going wrong with your code and how to fix it step by step.
The Core Issue
Your current line:
countPalindromes ss = length filter (== isPalindrome) ss
is parsed by Haskell as ((length filter) (== isPalindrome)) ss — which doesn't make sense for two key reasons:
lengthexpects one argument: a list whose length you want to calculate. Instead, you're passing itfilter(a function) as the first argument, which isn't valid.(== isPalindrome)is misplaced here. We don't need to compare anything to theisPalindromefunction itself; we just need to useisPalindromedirectly as the check (predicate) forfilter.
The Fixes
We need to first filter the input list to keep only palindromic strings, then pass that filtered list to length. Here are a few clean, idiomatic ways to write this:
1. Explicit Parentheses (Clear Grouping)
Use parentheses to group the filter call first, then pass its result to length:
countPalindromes :: [String] -> Int countPalindromes ss = length (filter isPalindrome ss)
This makes it explicit: we first run filter isPalindrome ss to get all palindromic strings, then calculate the length of that resulting list.
2. Use the $ Operator (Avoid Parentheses)
Haskell's $ operator lowers the precedence of function application, letting us skip nested parentheses. It works like f $ x = f x, but it evaluates the right-hand side first:
countPalindromes ss = length $ filter isPalindrome ss
3. Point-Free Style (Idiomatic & Concise)
Since the input ss appears on both sides of the equation, we can use function composition (.) to write this without explicitly naming ss:
countPalindromes :: [String] -> Int countPalindromes = length . filter isPalindrome
This reads as "compose the length function with filter isPalindrome" — it takes a list, filters out non-palindromes, then returns the length of the remaining list.
Quick Note on Your isPalindrome Helper
Great job on this part! w == reverse w is a clean, idiomatic way to check if a string is a palindrome in Haskell — no changes needed here.
内容的提问来源于stack exchange,提问作者Aelin

