Stormy
Stormy

Reputation: 169

Haskell: error taking in list of tuples -> outputting list of tuples

So I'm having a blast working through a Haskell tutorial... one challenge is to:

"Write a Lambda expression and map, to take a list of tuples and produce a list of tuples. The list contains the lengths of two sides of right triangles, a and b. Produce a list that contains the length of all three sides, where the third side is c, found with the Pythagorean Theorem" (of course).

With example input/output like:

[(3,4),(5,16),(9.4,2)]
== [(3.0,4.0,5.0),(5.0,16.0,16.76305461424021),(9.4,2,9.610411021387172)]

So I did some practice stuff first, like just getting the correct answer to the Pythagorean theorem, then taking in a tuple but outputting as usual, then taking in and putting out a tuple -- that all worked, eventually getting to this Lambda expression:

pythagLambdaTupleInOut = (\(a,b) -> (a,b,(sqrt $ a^2 + b^2)))

It compiled and produced this:

ghci > pythagLambdaTupleInOut (3,4)
(3.0,4.0,5.0)

So it works... So then I tried:

pythagLambdaListTupleInOut = (\[(a,b)] -> [(a,b,(sqrt $ a^2 + b^2))])

It compiles, but this happens when I try to use it:

ghci > pythagLambdaListTupleInOut [(3,4),(5,16)]
*** Exception: six.hs:1376:31-68: Non-exhaustive patterns in lambda

Any clues what I'm missing? Is it something with map? I wasn't sure how to work map in there, based on the examples in the tutorial...

Haskell, btw, is fascinating and so cool!

Upvotes: 2

Views: 181

Answers (1)

talex
talex

Reputation: 20524

Function you looking for is

pythagLambdaListTupleInOut = map (\(a,b) -> (a,b,(sqrt $ a^2 + b^2)))

your version fails because [(a,b)] pattern mean list with single element, and that element is tuple. When you pass list with two tuple haskell unable to pattern match.

Upvotes: 7

Related Questions