Reputation: 61
I am a newby to Haskell and I am trying to create a function that takes a triple and returns an array of triples, like so:
tripleVariations 1 (0,0,0)
=> [(1,0,0), (0,1,0), (0,0,1)]
I understand how to match to a specific value in the triple with pattern matching and I even created a custom function that maps a function over a triple, but I don't understand how to replace one value of the triple, add that to the array and then continue to the next value in the triple. I find that I tend to try and solve these problems too much according to imperative paradigm, which is exactly what I'm trying to avoid. Any help is welcome, thanks!
Upvotes: 0
Views: 223
Reputation: 58878
Surely you can just write it:
tripleVariations w (x,y,z) = [(w,y,z), (x,w,z), (x,y,w)]
If you wanted this to work with any size tuples, it would be more complicated... but you don't, so why waste the effort?.
According to Haskell: how to map a tuple? there is no way to iterate over a tuple because tuples can have diferent types in them. It wouldn't make sense to iterate over the type (Int, String, Char)
for example. If you want to write code that works with tuples where every part has the same type, presumably you should use a list instead of a tuple.
Upvotes: 3