Stefan Flondor
Stefan Flondor

Reputation: 369

swap two elements in Haskell by value

I'm new to Haskell. I need a function to swap two elements in a list when I know only the values.

For example:

swap 5 6 [1,5,7,6,4,3,2] -> [1,6,7,5,4,3,2]

5 and 6 are the values not the index, and the index of the values can be any.

Upvotes: 0

Views: 4490

Answers (2)

Jeff Foster
Jeff Foster

Reputation: 44706

It might help if you think about this task as reconstructing the list with the values swapped. The type signature is going to be like this. You're taking in two numbers to be swapped, and a list.

swap :: Int -> Int -> [Int] -> [Int]

You've got a couple of cases now. If the list is empty, that's easy. This is your base case.

swap _ _ [] = []

If the list isn't empty, then you've got two choices. Either the head of the list is a number you are interested in, or it's not. In the case where it matches, swap the value, otherwise just rebuild the list.

swap n m (x:xs)
  | n == x = m : (swap n m xs)
  | m == x = n : (swap n m xs)
  | otherwise = x : (swap n m xs)

Once you've got this situation, you can see that you're doing an operation on every element. Now you can convert it over to the map solution (which is far more idiomatic!).

Upvotes: 7

Manuel Eberl
Manuel Eberl

Reputation: 8278

swap a b = map (\x -> if x == a then b else if x == b then a else x)

EDIT: Ah, I am afraid I only noticed that this question was answered in a comment above in the exact same way after I posted my answer. Apologies.

Upvotes: 5

Related Questions