Firstmost, I am just getting started with functional programming so I would appreciate corrections in any terminology I may have used incorrectly.
Story time, While doing a Project Euler Problem 1 in Haskell I came to a solution that look roughly like
sum [3,6..999] + sum [5,10..999] - sum[15,30..999]
Which each sum is evaluated into
foldl (+) [x1,x2,x3,x4,x5,x6,etc] -- yep, the sum is evaluated one element at a time
However, at least in Haskell, you cannot pattern match and grab the arguments from another function. The basic idea would be whether sum should be intelligent enough to recognize known mathematical formula for optimization of calculation by evaluating other functions itself:
-- Doesn't work; didn't intend to; not valid Haskell -- Try known formulas first if the list generator is known -- This would match sum [1..100] and return 5050 in O(1) sum `EnumFromTo` 1 n = n*(n+1)/2 -- If the sum is not recognized then it would do it 1 by 1 as a fallback in O(n) -- This is the current and only implementation of sum sum = foldl (+) 0
I would guess it would be easier, more straightforward, and betterstyle to define a new sum function with a different name that covers the given formula such as
sumTo n | n >= 1 = n*(n+1)/2
But conceptually speaking
- Is redefining specific functions from within another function possible?
- Would allowing this break something?(IE, in this case, "EnumFromTo 1 n" would not be evaluated, but sum would still return the correct result)
- Are there any examples of this evaluation scheme?
- Is this a concept any programming language implements?