Basic Haskell Summation

I do Haskell and write a summing function that takes two numbers (upper and lower limits) and sums.

those. summation 0 10 will return 55

I can make it work mostly, but I can’t figure out how to get it using only two parameters.

Here is what I still have:

 summation :: Integer -> Integer -> Integer -> Integer summation xy sum = if (y<x) then sum else summation x (y-1) (sum+y) 

So this works fine, but I need to do summation 0 10 0 so that it works correctly. I'm not sure how I can get this to work with only two parameters in Haskell.

+4
source share
3 answers

You will wrap it.

 summation :: Integer -> Integer -> Integer summation xy = summation' xy 0 summation' :: Integer -> Integer -> Integer -> Integer summation' xy sum = if (y<x) then sum else summation' x (y-1) (sum+y) 
+10
source

Quick response:

One easy way is to use the sum function from Data.List .

Then you could just say:

 summation xy = sum [x .. y] 

This solution assumes x less than y , and you can fix it by saying:

 summation xy = sum [min xy .. max xy] 

Definition of sum :

As you study Haskell, it may be important to know how sum works and not just to know that it exists. For me, the biggest hurdle to get started was to write too many functions that already existed; especially since I did not know how to write them effectively.

Hoogle is a big help in this regard: it is a search engine that allows you to browse Haskell features. This is great for performance, because you can spend time working on your problem, instead of creating bad rewrites of half the foreplay. This is also great for learning, because there are links to the source code of most functions on Hackage . The source code for Prelude and other "fundamental" libraries, such as Data.List , is surprisingly accessible to beginners and will give a lot of information about how "smart children" do something.

The :browse command in GHCI is something that I recently learned about, which, as I would like, I discovered earlier.

In any case, one way to determine sum is to use a fold:

 sum xs y = foldl (+) 0 xs 

Or the equivalent in a "meaningless" style :

 sum = foldl (+) 0 

I usually prefer the first wording, but knowing how and why the second works will help you on your journey.


Further reading:

You will notice that I used the foldl function. This function collapses the input list. To β€œmaster” functional programming, knowing how to fold is one of the most basic and important concepts. A good resource for advice is the fold page from the Haskell Wiki .

+10
source

You could do it like Gauss did.

 summation begin end | end < begin = summation end begin | otherwise = n * (2*a + (n-1)*d) `div` 2 where a = begin d = 1 n = end - begin + 1 

The code is clearly a literal translation from http://mathcentral.uregina.ca/QQ/database/QQ.02.06/jo1.html (a little down this page: S = n[2a + (n-1)d]/2 )

+4
source

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


All Articles