Reputation: 1742
For Project Euler Question #1, the shortest one-liner in GHCI is:
sum [3,6..9999] + sum [5,10..9999] - sum [15,30..9999]
I found this after I solved the problem is a much bloody way. However, since I am new to Haskell, I decide to see if I could take this and put it together as a set of function returning similar answer to any value of x (step value, i.e. '3' or '5' above] and y (length of the list).
I have the first function done here:
sumList :: (Enum a, Num a) => a -> a -> a
sumList a b = sum[a,a+a..b]
Next I was trying to take this function and do something such as sumListTotals [3,5] 1000
for example from the question. This would all sumList
for each item in the list then one subtract the duplicate numbers (i.e. [15,30..1000] using the example.
I am not looking for someone to actually solve it but to help me in pointing me in the proper direction.
I was attempting to use the map
function something like below:
sumListTotals list = map f list
where f = sumlist a b
But, I am unsure how to pull out the stuff from the list or if I do something like sumListTotals ([3,5],1000)
or am I completely on the wrong track here?
Update per @user5402:
module Project1 where
import Data.List (union)
sumListTotals :: (Enum a, Eq a, Num a) => a -> a -> a -> a
sumListTotals a b c = sum $ union [a,(*2)a..c] [b,(*2)b..c]
Upvotes: 2
Views: 416
Reputation: 52057
You're on the right track:
sumListTotals a b c = sum [a,a+a..c] + sum [b,b+b..c] - sum[m,m+m..c]
where m = ...???...
I'll leave you to figure out the definition of m
since that's really a number theory problem and not a Haskell programming problem.
Clearly for a = 3, b = 5
m
should be 15
. But what should m
be for a = 3, b = 3
?
Upvotes: 1