Reputation: 4149
I am having trouble writing a function which deletes an element from a list within a tuple.
The problem is, I would like the function to return the tuple. However, using the delete
function from Data.List
gives me a list.
Code:
-- type Value = Int
type Cell = (Int, [Int])
type Board = [Cell]
----------- your solution goes here --------------
-- solvem :: Board -> Board
-- solvem bd = ???
deleteCandidate :: Int -> Cell -> Cell
deleteCandidate cand c1 = delete cand (snd c1) -- This gives me trouble
updateNeighbors :: Cell -> Cell -> Cell
updateNeighbors c1 c2 | isNeighbor c1 c2 = deleteCandidate (head (snd c1)) c2
| otherwise = c2
Since data in Haskell is immutable, how would I return a tuple in deleteCandidate
function? Would I have to reconstruct a Cell?
Upvotes: 1
Views: 280
Reputation: 91907
Simply pattern-match the tuple to extract the two pieces, operate on one of them, and then put it back together into a new tuple:
deleteCandidate :: Int -> Cell -> Cell
deleteCandidate cand (x, xs) = (x, delete cand xs)
Alternatively, since (a,)
has a Functor
instance, you could write
deleteCandidate :: Int -> Cell -> Cell
deleteCandidate cand = fmap (delete cand)
Or, shorter still, you could elide the explicit cand
argument as well, and express deleteCandidate as a simple function composition:
deleteCandidate :: Int -> Cell -> Cell
deleteCandidate = fmap . delete
Personally I like the second version best, because I find it hard to think about how this composition works, and how it's different from (fmap delete)
.
Upvotes: 6