Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - mapping the odd placed values and the even placed values differently

is there an easy way. To take a list of numbers, say 123456. Then multiply the odd placed by three and the even placed by 1.

i.e. (1 * 3) + (2 * 1) + (3 * 3) + (4*1) + (5*3) + (6*1)

i was thinking the map function somewhere along the lines. But i don't know how to map *3 to just the odd placed values. Oh and if you could give me the version not in prelude that would be great like the actual function or functions, as if its being imported from an external haskell file

Thanks for the help

like image 984
Abstract Avatar asked May 31 '10 07:05

Abstract


People also ask

How does map function work in Haskell?

The map() function takes two parameters namely a list and the function to be applied on each element in the list and returns a new list as the output. The map() function is available in Data. Map module in Haskell programming language.

Can Haskell lists have different types?

Haskell also incorporates polymorphic types---types that are universally quantified in some way over all types. Polymorphic type expressions essentially describe families of types. For example, (forall a)[a] is the family of types consisting of, for every type a, the type of lists of a.


1 Answers

Okay, as I wrote in a comment earlier, zipWith (*) (cycle [3,1]) xs is what you're looking for. But first, a minor nitpick: the head of the list I would call the zeroth element, that's why I have switched the 1 and 3 around :-)

Let's go through a simple example; let xs be [9,8,7,3,2]. cycle [3,1] just repeats its argument over and over so that will be an infinite list starting with [3,1,3,1,3,1,..]. What zipWith f xs ys does is take the head element of xs and the head element of ys and apply f (which should be a function of two arguments) to those elements - the result of f then goes onto the front of the result of zipWith. If one of xs or ys becomes empty, we're done; otherwise we just keep going.

So the first element of the result will be (3 * 9), then (1 * 8), (3 * 7), (1 * 3), (3 * 2) and we're done!

You can have a look at the definition of zipWith here.

If you really don't want to use the predefined functions, you could define an 'alternating map' taking two functions instead of one, applying the first of these to the head of your argument list and switching the functions around on the recursive call. I'll let you figure out the details there...

like image 177
yatima2975 Avatar answered Oct 22 '22 02:10

yatima2975