You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell:统计字符串列表中回文数量的函数错误修复咨询

Fixing the 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:

  • length expects one argument: a list whose length you want to calculate. Instead, you're passing it filter (a function) as the first argument, which isn't valid.
  • (== isPalindrome) is misplaced here. We don't need to compare anything to the isPalindrome function itself; we just need to use isPalindrome directly as the check (predicate) for filter.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:49:42