Home > Enterprise >  Haskell Function to multiply elements in a list
Haskell Function to multiply elements in a list

Time:09-17

dobb[] = []
dobb (x:xs) = [x * 2| x<- xs]

I am really new to haskell and started learning it this week. I want to create a function that multiplies each element in a list by 2. So the list would go from [1,2,3] to [2,4,6]. The code I have works fine, except it skips the first element of the list and goes from [1,2,3] to [4,6]. How can I make the code multiply the first element as well?

[x*2 | x<-[1..5]]

I've found this line that does what I am looking for, but I dont understand how to go from this line of code and convert it to a function that works for all lists.

CodePudding user response:

I'll address your last question,

how to go from this line of code,

      [x*2 | x <- [1..5]]

and convert it to a function that works for all lists[?]

This is known as generalization and is achieved by abstraction. First we name it,

foo = [x*2 | x <- [1..5]]

then we name that arbitrary piece of data we used as an example to work on,

foo = let {xs = [1..5]} in [x*2 | x <- xs]

and then we abstract over it by removing that arbitrary piece of data in the internal definition, letting it become the function parameter instead, to be specified by this, now, function's callers:

foo        xs           =  [x*2 | x <- xs]

and there it is, the general function working on all lists, doing the same thing as it did on the specific example we used at first.

CodePudding user response:

If you use the pattern (x:xs) then you unpack the list such that x is the head (first item) of the list, and xs is the tail (remaining items) of that list. For a list [1,4,2,5], x will thus refer to 1, and xs to [4,2,5].

In the list comprehension, you then use x <- xs as a generator, and thus you enumerate over the remaining elements. The x in the list comprehension is furthermore not the head of the list, but a more locally scoped variable.

You can work with list comprehension and work on the entire list, so:

dobb :: Num a => [a] -> [a]
dobb xs = [x * 2| x <- xs]

We can also work with map :: (a -> b) -> [a] -> [b] to perform the same operation on the elements:

dobb :: Num a => [a] -> [a]
dobb = map (2*)
  • Related