I’m trying to make a function that does the following: it gets a list for example [1,4,2,3] and it gives a list back [3,2,1].
Because 1 - 4 = 3 (abs value), 4 - 2 = 2 and 2 - 3 = 1.
I thought this piece of code would do that except for the abs value.
function :: [a] -> [a]
function [] = []
function (x:xs) = [x - head(xs)] ++ function xs
but it’s giving me errors and I don’t find any solution.
Kind regards,
EDIT:
Thank you guys, learned so much today. Indeed i’m a beginner, i’m having a course on university that gives me prolog,haskell, scala, python,aspectj and metaprogramming. So we have per program lang 2 lessons off 2 hours and afterwards some time to make some exercices.
Next monday i have exam and zipwith, etc… we must write our own function. But thanks for the good explained tutorial, learned so much. This is the working solution:
function :: Num a => [a] -> [a]
function (x:y:xs) = [abs(x - y)] ++ function (y:xs)
function _ = []
If you are still interested in recursive solution.
So
(-) :: Num a => a -> a -> aoperator requires, that it’s arguments should beNum. So we can fix it withfunction :: Num a => [a] -> [a].Now we have another problem:
So we should handle some cases:
But it’s still not what we actually expected:
So we should add
absfunction:Done
Beside that you can do that really easy and with more readable code.
How can you find a difference between two lists?
zipWithlooks really helpful here. For example:So idea is to
zipWith (-)original list and it’stail.And your
functioncould like like that:Done