
Hey all! I compared the different methods proposed with my eyes and the profiler. sumCheck1 _ [] _ = Nothing sumCheck1 total (x:xs) ys = if total' == Nothing then sumCheck total xs ys else return (x,(ys!!(fromJust total'))) where total' = elemIndex (total-x) ys sumCheck2 total (x:xs) ys = let diff = total - x in if elem diff ys then Just (x,diff) else sumCheck total xs ys sumCheck3 i as bs = not $ null [(x,y) | x <- as, y <- bs, x+y==i ] It is fascinating how small the code can be with list comprehensions. Unfortunately the third solution needs much more memory during run time than the other two. Increasing the list size leads to heavy growth of memory allocation. Probably the evaluation of the cross product in sumCheck3 is not very lazy (but why not?). The first two solutions scale very well. Cheers On 07/26/2011 08:31 AM, aditya siram wrote:
List comprehension seems like the easiest way to do it.
First here's how to get the cross product of two lists, I'll be using this below: cp as bs = [(x,y) | x<- as, y<- bs ] -- cp [1,2,3] [4,5,6] = [(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]
Then constrain the cross product to tuples where the sum is the given number: sums i as bs = [(x,y) | x<- as, y<- bs, x + y == i] -- sums 4 [1,2,3] [1,2,3] == [(1,3),(2,2),(3,1)]
Then check that the list of constrained sums is not empty: sumCheck i as bs = not (null (sums i as bs))
-deech
On Mon, Jul 25, 2011 at 10:52 PM, Bryce Verdier
wrote: Hi all, I'm new to haskell, and I'm trying to get better with it. Recently I completed one of the challenges from Programming Praxis and I was wondering if people would be willing to spend some time and tell me how I could improve my code. Thanks in advance, Bryce Here is a link to the programming praxis: http://programmingpraxis.com/2011/07/19/sum-of-two-integers/ And here is my code: import Data.List import Data.Maybe sumCheck :: Int -> [Int] -> [Int] -> Maybe (Int, Int) sumCheck _ [] _ = Nothing sumCheck total (x:xs) ys = if total' == Nothing then sumCheck total xs ys else return (x, (ys !! ( fromJust total'))) where total' = (total - x) `elemIndex` ys
_______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners
_______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners