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

I am trying to find a way to do something like this:

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

to get a tuple (1, 3) as an output.

Apparently, in theory, it looks like an applicative functor, but a little back. I suppose there is a similar function that does this (or some way of creating it), but I cannot find / understand it.

I tried to define a function like this:

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

but the GHC does not actually compile this.

Any help would be great; thanks!

Edit (whole year!):

My fmap' will not compile because the type signature was incorrect. Obviously there are better ways to do what I am doing, but my fmap' type should be as follows:

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

In this case, it compiles and works just fine.

+6
source share
4 answers

I think you can do it with arrows.

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

will return (1,3) .

+15
source

Apparently, in theory, it looks like an applicative functor, but a little back.

Actually, this is a boring old forward applied functor; in particular, the reader ((->) r) .

 Prelude Control.Applicative> liftA2 (,) head last [1,2,3] (1,3) 

Or if you do these things:

 Prelude Control.Applicative> let sequenceA [] = pure []; sequenceA (x:xs) = (:) <$> x <*> sequenceA xs Prelude Control.Applicative> [head, last] `sequenceA` [1,2,3] [1,3] 
+9
source

The fmap' type fmap' invalid. It should be

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

or, it may be more generalized

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

It is not like fmap :: (a -> b) -> fa -> fb .

+4
source

Something to try in this situation is to omit the type signature and check what the GHC is.

Doing this and calling GHCi :t fmap' gives a signature

 fmap' :: (t2 -> t, t2 -> t1) -> t2 -> (t, t1) 

which is identical to the generic version of KennyTM and will give you the behavior you are looking for.

+3
source

Source: https://habr.com/ru/post/921520/


All Articles