0

I want to make a function that selects the given indexed elements from a list.

For example:

reconstruct' [1,4] "bear" = [br]
reconstruct' [2,3,4] [1,2,3,4,5] = [2,3,4] 

Function definition:

reconstruct' :: [Int] -> [a] -> [a]
reconstruct' _ [] = []
reconstruct' (x:xs) l = [place (x-1) l ] ++ (reconstruct' (xs) l)

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

My function is almost working, however after giving back the right elements, instead of closing the list it gives an error: [2,3,4*** Exception: Non-exhaustive patterns in function reconstruct'

How could i fix this?

bereal
  • 32,519
  • 6
  • 58
  • 104
3t893w
  • 297
  • 3
  • 5
  • As you are juste prepending one element, you could simplify to: `reconstruct' (x:xs) l = (place (x-1) l ) : (reconstruct' (xs) l)` – jpmarinier May 09 '22 at 14:17
  • 1
    If you compile with warnings turned on (`-Wall`), GHC should warn you and list the missing case(s). It's very useful! – chi May 09 '22 at 14:39

1 Answers1

4

You are not capturing the situation when the list of indices is empty:

reconstruct' [] _ = []
bereal
  • 32,519
  • 6
  • 58
  • 104