生成其他列表中的差距列表.键入错误阻止我,



我正在尝试创建一个函数来列出另一个列表的差异。因此,对于 [1,3,7,11],它将返回 [2,4,4]。我正在尝试使用列表理解,但是我想要使用的函数的类型遇到了麻烦。是否有可能通过将 [t] 转换为 [int] 并再次转换回 [t] 来保留这种格式?

{ 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]) : []

zipWith怎么样:

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

编辑(由于下面的评论(:

更具体的函数声明可能如下所示:

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

我想桑切斯@Daniel 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

最新更新