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

Haskell函数出现非穷举模式问题:如何修复索引元素选取函数的报错?

Fixing the Non-Exhaustive Patterns Error in Your Haskell reconstruct' Function

Let's break down what's going wrong and fix it step by step.

The Root Cause

Your reconstruct' function currently only handles two cases:

  1. When the input list l is empty (reconstruct' _ [] = [])
  2. When the index list has elements left (reconstruct' (x:xs) l = ...)

But you're missing a critical case: when the index list is empty (reconstruct' [] l). When your recursive call processes all elements in the index list and reaches reconstruct' [] l, Haskell can't find a matching pattern, hence the "Non-exhaustive patterns" exception.

Fixing the Recursive Version

All you need to do is add a pattern to handle the empty index list. Here's the corrected code:

reconstruct' :: [Int] -> [a] -> [a]
reconstruct' [] _ = []  -- Handle empty index list
reconstruct' _ [] = []
reconstruct' (x:xs) l = place (x-1) l : reconstruct' xs l  -- Replaced ++ with : for efficiency

place :: Int -> [a] -> a
place _ [] = error "Index out of bounds"
place y (x:xs)
  | y <= 0    = x
  | otherwise = place (y-1) xs

A small bonus: I swapped [place ...] ++ ... for place ... : ... because ++ is less efficient for building lists incrementally—using the cons operator (:) is the idiomatic Haskell approach here.

A More Idiomatic Alternative

Since your function is essentially mapping each index in the first list to the corresponding element in the second list, you can simplify it using map instead of explicit recursion. This avoids pattern matching mistakes entirely:

reconstruct' :: [Int] -> [a] -> [a]
reconstruct' indices lst = map (\i -> place (i-1) lst) indices

place :: Int -> [a] -> a
place _ [] = error "Index out of bounds"
place y (x:xs)
  | y <= 0    = x
  | otherwise = place (y-1) xs

Testing the Fix

Now let's verify your examples work as expected:

  • reconstruct' [1,4] "bear" returns "br" (I think your example had a typo with [br]—strings are just lists of chars in Haskell)
  • reconstruct' [2,3,4] [1,2,3,4,5] returns [2,3,4]

Both cases will run without throwing the non-exhaustive patterns exception now.

内容的提问来源于stack exchange,提问作者3t893w

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 20:37:42