Create a list of spaces in other lists. Type error holding me

I am trying to create a function that lists the differences in another list. So for [1,3,7,11] he will be back [2,4,4]. I am trying to use list comprehension, but I am having problems with the types of functions that I wanted to use. Is it possible to save this format by converting [t] to [int] and back to [t] again?

{ difflist x y = [ p - q | p<- [x..y],

                           q<- [ ( [1..(length [x..y]) ] !! [x..y] ): []]] }



<interactive>:200:70: error:
     Couldn't match expected type ‘Int’ with actual type ‘[[Int]]’
     In the second argument of ‘(!!)’, namely ‘[x .. y]’
      In the first argument of ‘(:)’, namely
        ‘([1 .. (length [x .. y])] !! [x .. y])’
      In the expression: ([1 .. (length [x .. y])] !! [x .. y]) : []
+4
source share
2 answers

How about zipWith:

Prelude> let diffList = \x -> zipWith (flip (-)) x (tail x)
Prelude> diffList [1,3,7,11]
[2,4,4]

Edit (due to comments below):

A more specific function declaration may be as follows:

diffList :: Num a => [a] -> [a]
diffList [] = []
diffList l@(_:xs) = zipWith (-) xs l
+9
source

, @Daniel Sanchez zipWith .

diffs :: Num a => [a] -> [a]
diffs []     = []
diffs (x:xs) = zipWith (-) xs (x:xs)

, , , mapAccumL. :

diffs :: Num a => [a] -> [a]

diffs [] = []
diffs    = tail.snd.mapAccumL (\a x -> (x,x-a)) 0
+2

Source: https://habr.com/ru/post/1673385/


All Articles