Haskell中实现递归crosssum函数遇线程终止问题求助
Fixing the
crosssum Recursive Function: Resolving "Thread Killed" Error First off, that "thread killed" error almost always means your recursion is infinite—the function never hits a base case to stop calling itself. Let's break down how to fix this properly, sticking strictly to the allowed functions.
The Correct Recursive Implementation
Here's the working version of crosssum that follows all your constraints:
crosssum :: Int -> Int crosssum n | n <= 9 = n -- Base case: single-digit number is its own crosssum | otherwise = (n mod 10) + crosssum (n div 10)
Let's Walk Through Why This Works
- Base Case: When
nis a single-digit number (n <= 9), we just returnndirectly. This stops the recursion from going on forever. - Recursive Step:
n mod 10grabs the last digit of the number (e.g., 12 mod 10 = 2)n div 10removes the last digit (e.g., 12 div 10 = 1)- We add those two results together, recursively calculating the crosssum of the truncated number.
Testing with Your Example
Calling crosssum 12 will:
- First check 12 > 9, so compute 2 + crosssum 1
- Then crosssum 1 hits the base case, returns 1
- Final result: 2 + 1 = 3, which is correct.
Why Your Original Code Crashed
If you got a thread killed error, it's likely you missed the base case for single-digit numbers, or had a wrong condition (like using n > 0 instead of n <=9 without handling the single-digit stop). Without that base case, the function keeps calling itself on smaller and smaller numbers until the stack overflows.
内容的提问来源于stack exchange,提问作者gewissen
相关产品推荐
相关产品推荐

