Access to fields in tuples

I teach myself Haskell, and while it was the most enlightening experience, I find some things that are easy to do in the C language family that still remain a mystery. So here is my main problem. I want the function to retrieve tuples with a specific field equal to the given value. While I have this code

withJob :: [(String, String, String)] -> String -> [String] withJob [] _ = [] withJob ((_,_,x):xs) job | job == x = x:(withJob xs job) | otherwise = (withJob xs job) users :: [(String, String, String)] users = [("Jack", "22", "Programmer"), ("Mary", "21", "Designer"), ("John", "24", "Designer")] 

When calling users 'withJob' "Programmer" it outputs ["Programmer"] , but I would like it to output [("Jack", "22", "Programmer")] , however I don’t know how to access to tuples, not job ( x ) in job == x = x:(withJob xs job)

+4
source share
2 answers

Use @patents for this:

 withJob :: [(String, String, String)] -> String -> [(String, String, String)] withJob [] _ = [] withJob ( t@ (_,_,x):xs) job | job == x = t : withJob xs job | otherwise = withJob xs job 
+8
source

To expand on what @Ingo was getting: it would be more idiomatic for Haskell to write:

 jobField :: (String, String, String) -> String jobField (_, _, j) = j withJob :: [(String, String, String)] -> String -> [(String, String, String)] withJob xs job = filter (\x -> jobField x == job) xs 

We can go further:

 data Person = Person { pName :: String, pAge :: Int, pJob :: String } filterbyJob :: String -> [Person] -> [Person] filterbyJob job xs = filter (\p -> pJob p == job) xs 

And even then:

 filterbyJob :: String -> [Person] -> [Person] filterbyJob job = filter (\p -> pJob p == job) 

Or even:

 filterbyJob :: String -> [Person] -> [Person] filterbyJob job = filter ((== job) . pJob) 

At this point, if no one will use filterByJob horribly, it probably does not provide real value, except to just write filter ((== job) . pJob) where you need it!

The point of this exercise is that there is a powerful filter function that you can simply use rather than rewrite this code each time. This not only saves you time and code, but by reusing the well-known feature, you will make it easier for future programmers to understand the code (including your future!)

+4
source

All Articles