When to use arguments over parameters
Hi all.
In what cases would it be appropriate to pass an input to a function as an argument rather than as a parameter? One situation where it seemed appropriate was if you only know the type of the input at runtime - but
fn
functions require you to specify types for arguments anyhow.7 Replies
If you know the value at compile time, that is when parameters are appropriate, otherwise use arguments.
Example
Which can then be called as
you meant the other way around, right? Parameter are compile time values.
yep sorry
flip what i said
The purpose of function parameters is to facilitate metaprogramming—i.e. programs that generate programs. If you don't need to do that, then you don't need parameters.
(Perhaps your next question would be: when do I want a metaprogram?)
Functions with parameters (metaprograms) are useful when you want/need the compiler to generate many variations of a function. Generic functions (i.e. functions that can operate on arguments of many different data types) are a common use-case for this.
Note that Mojo's parameters don't work the same way as "type parameters" in Python, despite both of these features using the same syntax. Python type parameters are just "hints" and don't affect code generation, whereas in Mojo, every time you call a parametric function with different parameter values, a brand new copy of the function is emitted by the compiler, specialized to those particular values.
Does Mojo have JIT compilation capabilities to instantiate (i.e. compile) a parameterized function or structure with runtime values?
Parameters, by Mojo’s definition, is resolved/evaluated at compile time; functions monomorphised, no runtime polymorphism happening. But maybe you are asking about existentials?
Yeah, Parameters are resolved at compile time, but a lot of other DLS in Python uses JIT compilation to "transform" a runtime variable into something that can be used as a compile-time variable.
My question was about JIT compilation capabilities in Mojo. I guess the topic is too far from the original question, so I'll move the discussion to another thread.