Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functor Design Pattern in Haskell

Tags:

haskell

I apologize for not coming up with a good title for this question. I'm having some trouble expressing what I need. I have a simple problem in Haskell and I am wondering what the best approach is to solve it.

Let's say I have a list of numbers: [-3,2,1,2]. I want to return the value with the highest absolute value. That is, I want to return -3. So I want:

f = maximum . map abs

The problem is, of course, that this returns the calculated value (3) and not the original value (-3).

I could figure out a way of doing this, maybe mapping the original list to a tuple of (originalValue, calculatdValue), finding the tuple whose snd is returned by my function (maximum) and then return fst of that tuple.

But this seems like a lot of "plumbing" for a simple problem like this, and I wonder if there is some abstraction I'm missing that solves this. That is, there is this generally procedure I do all the time, and I want some way of neatly doing it:

  1. I want to take a list of items.
  2. I want to map them to a certain value (let's say the absolute value)
  3. Then I want to select one based on some criteria (let's say I want the maximum or maybe the minimum).
  4. But then I want to return the original value. (If the list was [-3,2,1,2] and I want to return the value with the highest abs, then I would return -3).

Is there a library function for this? Is there a functor or a monad for this?

I think I want a function with the signature:

f :: ([b] -> b) -> (a -> b) -> [a] -> a

i.e.

f maximum abs [-3,2,1,2]

This feels very "functory" to me or maybe "monadic".

like image 256
Ara Vartanian Avatar asked Apr 01 '11 19:04

Ara Vartanian


People also ask

What is a functor in Haskell?

Functor in Haskell is a kind of functional representation of different Types which can be mapped over. It is a high level concept of implementing polymorphism. According to Haskell developers, all the Types such as List, Map, Tree, etc. are the instance of the Haskell Functor.

Is maybe a functor Haskell?

Another simple example of a functor is the Maybe type. This object can contain a value of a particular type as Just , or it is Nothing (like a null value).

What is functor?

A functor is a function which maps objects and morphisms from one category to objects and morphisms in another.

Is Fmap a functor?

The expression fmap (*2) is a function that takes a functor f over numbers and returns a functor over numbers. That functor can be a list, a Maybe , an Either String, whatever. The expression fmap (replicate 3) will take a functor over any type and return a functor over a list of elements of that type.


1 Answers

Use maximumBy which takes a comparison function. You can then pass some function that compares the way you want.

maximumBy (compare `on` abs)
like image 162
augustss Avatar answered Oct 05 '22 23:10

augustss