如何实现计算单词字母数量的函数?基于给定的stringLength函数签名
stringLength :: String -> Int in Haskell Got it, let's walk through how to build this function that counts the number of characters in a string. There are a couple of ways to do this, depending on whether you want a concise, idiomatic solution or want to dig into the recursive underpinning.
The Idiomatic Haskell Approach
Since in Haskell, a String is just a type synonym for [Char] (a list of characters), we can leverage the built-in length function directly. It's designed to work on any list, so it fits perfectly here:
stringLength :: String -> Int stringLength = length
That's it! This is the most Haskell-y way to do it—no need to reinvent the wheel when the standard library has exactly what we need.
Manual Recursive Implementation (For Learning)
If you want to understand how the length calculation works under the hood, you can write a recursive version using pattern matching:
stringLength :: String -> Int -- Base case: empty string has 0 characters stringLength [] = 0 -- Recursive case: take the first character (we don't care about its value, so use _), -- add 1 to the length of the remaining string stringLength (_:xs) = 1 + stringLength xs
Let's break this down:
- When we pass an empty string (
[]), we return 0—this stops the recursion. - For any non-empty string, we split it into the first character (
_) and the rest of the string (xs). We add 1 (for that first character) to the result of callingstringLengthon the remaining characters. This repeats until we hit the empty string base case.
Testing the Function
You can test it out with some examples to make sure it works:
main :: IO () main = do print $ stringLength "hello" -- Output: 5 print $ stringLength "" -- Output: 0 print $ stringLength "Haskell!" -- Output: 8
内容的提问来源于stack exchange,提问作者Eric Zhang

