3 ms·
This might be a bit off topic, but since we're talking about functional languages... I've done a very small amount of functional programming (I did the first 5
by Davertron 17y ago
This might be a bit off topic, but since we're talking about functional languages...
I've done a very small amount of functional programming (I did the first 5 or so problems from project Euler in Haskell, for example, just to see what Haskell was like), and there's one specific thing I was wondering about. First, let me give you some example psuedo-code just to describe the situation:
if function_call(value) == some_value_I_want_or_something ? return function_call(value); else return 0;
Ok, that's not any particular language or anything, but I think it'll serve to get my query across.
So in the above code, I want to do something like check the result of a function call, and then if that value is the one I want, return the result of that function call. Otherwise, return 0 (you could do whatever here, but I just made it simple...).
My question is this: do most functional languages do some sort of optimization to avoid basically calling the function twice, since in a purely functional language, functions shouldn't have side affects, so calling a function multiple times with the same input should yield the same output? In other words, does the runtime/compiler/whatever say "I just ran function_call(value) and got a result, and since I don't allow side affects, anytime from here on out that I see function_call(value), I'm just going to assume the result is the same."?
Maybe it's because I'm very inexperienced with functional languages, but I find that I run into that kind of situation often enough, and I always think "Is this going to be really slow because I'm basically calling this function twice even though the result is going to be the same?".
I'm guessing that this may vary language to language; as I understand it, for example, Lisp is "functional", but not purely so, and doesn't really enforce the whole "no side-effects" thing, so it would have to run the function twice, but I could be mistaken.
- wlievens 17y agoYour pseudo-code is a little weird (it recurses infinitely?) but I think that what you're referring to is memoization, or basically caching your function calls' results for equivalent arguments. I don't know if any languages support it out the box, but I do know that any language with first-class functions and closures will allow you to make a simple "wrapper" construct so that you get this feature anyway.
- Davertron 17y agoNah, it doesn't actually recurse infinitely, it just looks weird. Here's an example in c: http://codepad.org/Xysob1jS http://codepad.org/Xysob1jS Obviously this is a totally contrived example but you get the idea.