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
benny
benny8mo ago
If you know the value at compile time, that is when parameters are appropriate, otherwise use arguments. Example
fn unary[negate: Bool](a: Int, b: Int) -> Int:
@parameter
if negate:
return a - b
return a + b
fn unary[negate: Bool](a: Int, b: Int) -> Int:
@parameter
if negate:
return a - b
return a + b
Which can then be called as
alias add = unary[False]
alias sub = unary[True]
alias add = unary[False]
alias sub = unary[True]
sora
sora8mo ago
you meant the other way around, right? Parameter are compile time values.
benny
benny8mo ago
yep sorry flip what i said
Nick!
Nick!8mo ago
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.
massimim
massimim8mo ago
Does Mojo have JIT compilation capabilities to instantiate (i.e. compile) a parameterized function or structure with runtime values?
sora
sora8mo ago
Parameters, by Mojo’s definition, is resolved/evaluated at compile time; functions monomorphised, no runtime polymorphism happening. But maybe you are asking about existentials?
massimim
massimim8mo ago
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.
Want results from more Discord servers?
Add your server