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
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With