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

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

  1. Base Case: When n is a single-digit number (n <= 9), we just return n directly. This stops the recursion from going on forever.
  2. Recursive Step:
    • n mod 10 grabs the last digit of the number (e.g., 12 mod 10 = 2)
    • n div 10 removes 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:00:31