Sunday, 15 February 2015

Haskell Invert Pair -



Haskell Invert Pair -

wondering if help writing function. trying create function inverts each "pair" in list.

module invert invert :: [(a,b)] -> [(b,a)] invert [(a,b)] = [(b,a)]

when come in invert [(3,1) (4,1) (5,1)]... supposed give me [(1,3) (1,4) (1,5)... gives me...

*invert> [(3,1) (4,1) (5,1)] <interactive>:2:2: function `(3, 1)' applied 2 arguments, type `(t0, t1)' has none in expression: (3, 1) (4, 1) (5, 1) in expression: [(3, 1) (4, 1) (5, 1)] in equation `it': = [(3, 1) (4, 1) (5, 1)]

since lists recursive info structures, have process list recursively in order swap elements, or utilize higher order function processing you. if define

invert [(a,b)] = [(b,a)]

it convert single-element lists, other inputs fail error!

try think input invert gets: it's either empty list, or non-empty lists. in case of non-empty list, can swap first element , convert rest recursively.

(if don't want invert invert yourself, use

invert = map swap

where swap data.tuple.)

haskell

No comments:

Post a Comment