开发者

About scanl1 in Haskell

开发者 https://www.devze.com 2023-02-05 07:29 出处:网络
A function should return the running sums of a list. Such as calling it with [1,2,3,5] returns [1,3,6,11].

A function should return the running sums of a list. Such as calling it with [1,2,3,5] returns [1,3,6,11].

I wrote this function like below:

sumlist' :: [xx]=[xx]
sumlist' []=[]
sumlist' [x]=x
sumlist' 开发者_运维百科xx=scanl1 (+) [xx]

When I run it in GHcI, it shows me that I do multiple declarations. So what's wrong with this function?


First off, you want to change the declaration to something like

sumlist' :: [xx]->[xx]

since sumlist' takes a List of type xx and returns a List of type xx.

Since we're using (+) in the call to scanl1, and (+) needs types of Num, we're going to need to scoot back to the definition of sumlist' and tell it that we specifically take lists of Nums.

sumlist' :: Num xx=>[xx]->[xx]

scanl1 can deal with empty lists, so all you need is

sumlist' :: Num xx=>[xx]->[xx]
sumlist' xx = scanl1 (+) xx


However, if you still, just for kicks, want to try your code, you'll need to fix the last two lines:

For the case where x contains 1 element, you have:

sumlist' [x] = x

Remember, sumlist' takes a list and returns a list, so just return the list back!

sumlist' [x] = [x]

And for the last case, where you take a list called xx, you have

sumlist' xx=scanl1 (+) [xx]

xx is already a list, so GHC will think [xx] is a list of lists, so just remove the brackets

sumlist' xx=scanl1 (+) xx

So our revised code is something like:

sumlist' :: Num xx=>[xx]->[xx]
sumlist' []=[]
sumlist' [x]=[x]
sumlist' xx=scanl1 (+) xx

As ephemient said, if you need to input multiple lines to GHCi, use the :load command.

Hope this helps, and happy hacking :-)


sumlist' :: [xx]=[xx]

That line is wrong. The part after the :: should be a type declaration, which looks like [a] -> [a]. (Yes, it looks like the pattern/value [xx], but isn't.)

Don't try entering multi-line declarations into GHCi, it treats each input line separately. Just save it in a file and :load the file from GHCi.


This isn't a direct answer to your question, but a better way to define sumList using higher order functions would be:

sumList :: (Num a) => [a] -> [a]
sumList = tail . scanl (+) 0

Note also that your type signature, despite the obvious mistaken = for ->, would have been "too polymorphic" in that your function only works on lists of "some type in the Num class", not "a list of any type".

0

精彩评论

暂无评论...
验证码 换一张
取 消