I am writing a Haskell function that takes a list of strings and returns a list containing the first two strings as a tuple as the result. So an example output would be:
listtuple ["bride", "zilla", "crazy", "women"] = [("bride", "villa")]
listtuple ["basketball", "football"] = [("basketball", "football")]
The way I was thinking of approaching it like so:
listtuple :: Eq a => [Str a] -> [(Str a, Str a)]
listtuple xs = [(x,y) | x <- xs !! 0, y <- xs !! 1]
Essentially I figured that I could just just pick the elements in the first and second indices of the list but I’m getting errors. Any help here?
What you probably wanted to do was this:
Note that this is NOT the same thing as what you wrote. The reason is that the list comprehension you wrote translates into the following:
This illustrates the issue: You are treating
xs !! 0andxs !! 1as lists when they are not lists.xs !! 0is just a single element, so if you want to declare thatxis equal toxs !! 0, you use:The
<-in list comprehension syntax does not do the same thing and I recommend you steer clear of list comprehensions until you understand how the list monad works, because the compiler translates list comprehensions to the list monad.Now, the second problem is that you use
(!!). You should steer clear of partial functions like(!!)and focus on using pattern matching to solve these things. The idiomatic way to do what you request would be to pattern match on the first two elements:… EXCEPT that will fail on lists that contain less than two elements. You guard against this by storing the result as a
Maybe, where aJustwraps a successful result, andNothingindicates failure: