Haskell技术问题:传递前序Peca元素实现元组列表转Peca列表
convert Function for Sequential Peca Conversion Let's break down why your current code isn't working, then fix it to meet your requirements.
The Problem with Your Current Code
In your updateTuple function, you're hardcoding previous = Dirt Ramp every time you process a tuple. That means all elements are being converted using the same initial Dirt Ramp value, instead of using the previously generated Peca as required. This is why your output doesn't match what you expect—each step isn't building on the last result.
The Solution: Use a Stateful Recursive Helper
Since each conversion depends on the previous Peca, we need a way to carry that state through the recursion. We'll use a helper function that tracks the last generated Peca and uses it for the next conversion.
Here's the corrected code (I've renamed your function to convert to match the required type signature):
convert :: [(Int,Int)] -> [Peca] convert [] = [] -- Handle the first tuple: it maps to Dirt Ramp, which becomes our initial state convert (_:restTuples) = firstPeca : convertHelper firstPeca restTuples where firstPeca = DirtRamp -- Adjust this if the first tuple needs gamaTipo (see note below) -- Helper function that carries the previous Peca state convertHelper :: Peca -> [(Int,Int)] -> [Peca] convertHelper _ [] = [] convertHelper previousPeca (currentTuple:remainingTuples) = let nextPeca = gamaTipo previousPeca currentTuple in nextPeca : convertHelper nextPeca remainingTuples
How This Works
- Main Function: For a non-empty list, we start with
DirtRampas the firstPeca(matching your requirement that the first tuple corresponds toDirt Ramp). We then pass this initialPecaand the remaining tuples to our helper. - Helper Function: This function takes the last generated
Pecaand the next tuple. It usesgamaTipoto create the nextPeca, then recursively calls itself with this newPecaand the remaining tuples. This ensures every subsequent conversion uses the prior result as input.
Note on the First Tuple
If the first tuple isn't just a placeholder for DirtRamp—and instead needs to be converted via gamaTipo from some initial Peca—adjust the main function like this:
convert :: [(Int,Int)] -> [Peca] convert [] = [] convert (firstTuple:restTuples) = let firstPeca = gamaTipo initialPeca firstTuple -- Replace initialPeca with the correct starting value in firstPeca : convertHelper firstPeca restTuples
You'll need to replace initialPeca with whatever starting value makes gamaTipo initialPeca (1,2) return DirtRamp (as per your professor's definition).
内容的提问来源于stack exchange,提问作者user12174294

