1

I want to use lambda to create a function that gets as parameter a list of pairs and returns a list of the first elements of the first list. Example:

function [ (1,2), (3,4) (5,6) ] = [1,3,5]

I'm using lambda like this but it doesn't seem to work:

firstall [] = []
firstall ((a,b) : xs) = (\(a,b) -> a : firstall(xs))

maybe I'm doing it totally wrong. Can someone help me?

2
  • 3
    You should ALWAYS use type signatures, especially when you are learning. If you had, you would realize that your code creates a list of functions. Haskell's type system is powerful and helpful; use it! In your case, you wanted firstall :: [(a,b)] -> [a]. See what happens when you add that. Commented Oct 12, 2015 at 23:21
  • What you want is map fst. Commented Oct 12, 2015 at 23:24

1 Answer 1

3

Your lambda expression simply is never called, you only define a lambda expression, you can call it with:

firstall ((a,b) : xs) = ((\(a,b) -> a) (a,b) : firstall(xs))

Now since you use a and b in your lambda expression as well, this is asking for trouble, a more accessible version is:

firstall ((a,b) : xs) = ((\(c,d) -> c) (a,b) : firstall(xs))

In other words you "unify" (c,d) with (a,b). You can use a and b in your lambda expression, but it makes things for yourself.


This being said, you can perform this task way easier:

firstall = map fst

which is short for:

firstall = map (\(a,b) -> a)

note that you don't need to specify an input parameter for firstall, since map fst is a function that will take as input a list.


Finally, as @DanielWagner suggests, you can simply drop the lambda expression:

firstall ((a,_) : xs) = (a : firstall(xs))

the underscore (_) means you are not interested in the value: you only need the first element of the tuple.

Sign up to request clarification or add additional context in comments.

1 Comment

An alternative fix to providing the lambda with an argument is to drop the lambda entirely, writing a : firstall xs instead of \(a, b) -> a : firstall xs (so that the whole line becomes firstall ((a,b) : xs) = a : firstall xs). I think that's probably closer to what DcCoO had in mind.

Your Answer

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