-2

I made a function in Haskell where I have a list of tuples, and want to extract only the second value of each tuple and return a list of the second values of the tuples.. I wrote this function but i get a weird error..

   --converts a list of tuples to single list
tupleToList :: [Stat] -> [Int]
tupleToList ((a,b):xs) =  b : tupleToList xs

I get an error on the ':' after(a,b) in the second line. Any ideas what might be causing the problem? The function itself doesn't appear wrong to me but I'm new to Haskell so maybe there's something I'm not following right.

7
  • by the way,'Stat' is a type which is a tuple of the form : (String,Int)
    – Hassan Ali
    Dec 18, 2015 at 17:23
  • 1
    "I get an error" - what error? The code seem fine to me as well. Maybe include a minimum working example (including imports, type defintions, etc). Dec 18, 2015 at 17:23
  • 4
    what you have is working here so the error is probably somewhere else in your file - btw: it seems as if you only want tupleToList = map snd anyway
    – Random Dev
    Dec 18, 2015 at 17:29
  • 2
    @HassanAli There is no parse error in the code you posted. Again, please include a minimum working example. Dec 18, 2015 at 17:30
  • 1
    I second the use of map snd . Your version doesn't handle empty list so it'll error out eventually. Dec 18, 2015 at 18:17

2 Answers 2

1

As others said there doesn't seem to be any error in what you wrote (other than what I noticed: you don't handle the case of an empty list.)

You asked in the comments how to rewrite it.

The simplest way is to do what Carsten said

tupleToList = map snd

If for some reason you wanted to build on your own version.

tupleToList :: [Stat] -> [Int]
tupleToList [] = []
tupleToList ((a,b):xs) =  b : tupleToList xs
0

You can do this extremely simply like this:

tupleToList = map snd

result:

> tupleToList [(1,"a"),(2,"b"),(3,"c")]
["a","b","c"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.