开发者

difference byproduct

I need to make a function with the signature di开发者_JS百科ffFolge :: (Integer, Integer) -> [Integer], which when applied to the argument pair (m, n) (m, n> 0) returns a descending list of numbers, the difference between the numbers beeing n. The first element of the Result list is m, the last but one element is always greater than 0 and the last element either 0 or a value strictly less than 0.

I write it as follows:

diffFolge :: (Integer,Integer) -> [Integer]
diffFolge (m,n) = if m > 0 && n > 0 then [m,m-n..n-2*n] else [] 

example

input  : diffFolge (5,1)
output : [5,4,3,2,1,0]

example

input  : diffFolge (5,2)
output :[5,3,1,-1]   ---> This is true by my code

However, with the input given in the first example my function returns [5,4,3,2,1,0,-1]. How can I correct this?


Haskell's [a..b] syntax returns a list including b if possible.

You could use [m, m-n .. 1-n], such that -n is excluded.

(BTW, n-2*n == -n)


Sometimes, it pays to do just a little bit of math. :)

diffFolge (m, n) = [m, m-n .. 1-n]

Also, it's unusual to use a tuple for multiple arguments to a function in Haskell. I would be more likely to write

df m n = [m, m-n .. 1-n]

And then, if for some reason I really need a function taking a tuple, I would write:

diffFolge = uncurry df


To me it also occurs that you've asserted m>=n So here's a quick Idea:

diffFolge :: (Integer, Integer) -> [Integer]
diffFolge (m,n)
    | m <= 0 || n <= 0 = []
    | n > m = diffFolge (n,m)    -- | Only if you want this case
    | otherwise = takeWhile (>= 0) $ iterate (\x->x-n) m


Not sure I understand what you want, but I am guessing this is it:

diffFolge  (m,n) | m <= 0    = [m]
                 | otherwise = m : diffFolge (m-n,n)

The error in your code is really the last element in your sequence, n - 2*n, note that this is equal to -n, so your list does not stop until you get an element which is strictly smaller than -n, but in the case where your list includes 0, the next to last element is 0 and the last element is -n. To fix this you can simply add 1 to it: [m,m-n..1-n]. Then if the list contains 0, -n is excluded, and if it does not contain 0, the last element is between 0 and 1-n.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜