use*_*287 4 indexing haskell list-comprehension list difference
我正在尝试创建一个列出另一个列表的差异的函数.因此,对于[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]) : []
Run Code Online (Sandbox Code Playgroud)
Net*_*ave 10
怎么样zipWith
:
Prelude> let diffList = \x -> zipWith (flip (-)) x (tail x)
Prelude> diffList [1,3,7,11]
[2,4,4]
Run Code Online (Sandbox Code Playgroud)
编辑(由于下面的评论):
更具体的函数声明可以如下:
diffList :: Num a => [a] -> [a]
diffList [] = []
diffList l@(_:xs) = zipWith (-) xs l
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
94 次 |
最近记录: |