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:
- When the input list
lis empty (reconstruct' _ [] = []) - 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

