Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to map tuple of functions over a list in Haskell?

I'm trying to do find a way to do something like this:

(head, last) `someFunction` [1, 2, 3]

to produce the tuple (1, 3) as output.

It seems similar in theory to an applicative functor, but a little backwards. I'm guessing there's a similar function that does this (or some way to make one), but I can't seem to find it/figure it out.

I tried defining a function like this:

fmap' :: ((a -> b), (a -> b)) -> [a] -> (b, b)
fmap' (f1, f2) xs = (f1 xs, f2 xs)

but GHC won't actually compile this.

Any help would be great; thanks!

Edit (a whole year later!):

My fmap' wouldn't compile because the type signature was wrong. Obviously there are better ways to do what I was doing, but the type of my fmap' should instead be:

fmap' :: ((a -> b), (a -> b)) -> a -> (b, b)

In that case, it compiles and runs just fine.

like image 552
Benjamin Kovach Avatar asked Jul 27 '12 19:07

Benjamin Kovach


People also ask

What is the difference between a map and a tuple?

Maps or hash tables are collections of key value pairs. Tuples are an immutable sequence of values and are used for aggregating values.

What does the map function do in Haskell?

map takes a function and a list and applies that function to every element in the list, producing a new list.

Are tuples immutable in Haskell?

A tuple is a sequence of values. The values can be of any type, and they are indexed by an integer, so tuples are not like lists. Tuples are immutable which means you cannot add more elements to the tuple as the program runs.

How do you make a tuple in Haskell?

Use parentheses and commas to create tuples. Use one comma to create a pair. Use more commas to create tuples with more components. Note that it is also possible to declare tuples using in their unsugared form.


1 Answers

I think you can do this with arrows.

head &&& last $ [1,2,3]

will return (1,3).

like image 79
Jeff Burka Avatar answered Sep 30 '22 02:09

Jeff Burka