LoginLogin
Nintendo shutting down 3DS + Wii U online services, see our post

How To Program #8 - Functions

Root / Submissions / [.]

haloopdyCreated:
IT'S MATH TIME AGAIN HOLY FFFFFFFFUDGE So maybe you've heard of functions in math. You know, f(x) and all that nonsense? Don't worry if you don't; we'll go over math functions in this lesson. You can make something similar in programming, and it's basically the WHOLE FOUNDATION of modern programming languages. In fact, original BASIC didn't even HAVE functions. SmileBoom (the company that made SmileBASIC) decided to add functions to a dead language in order to "modernize" it a bit. Seriously though, functions... they're SUPER important. Next tutorial (part 9)

Math Functions

So there's a bunch of definitions and theory and a whole load of other BS that goes with functions in mathematics... but screw all that crap. Functions are easy. Mathematical Functions are just a way of transforming one number into another. For instance, it might transform 2 into 4, 3 into 6, etc. Functions transform numbers in such a way that you can see the pattern of the transformation; for instance, a function might transform 1, 2, 3, 4, 5 into 3, 6, 9, 12, 15 (the function transformation is 'times 3'). The important thing about functions is that the transformation is ALWAYS the same for a given number. So if a function turns 2 into 4, it will ALWAYS turn 2 into 4.

How to write functions

Functions are written as equations. You know what equations are: equations just show that two things are equal. For instance, 2+2=4. You know that the left side (2+2) is equal to the right side (4) because (a) you know know to count and (b) there's A BIG OL' EQUALS SIGN BETWEEN THEM. This works nicely with constants (values that don't change; numbers like 4, 2, etc.), but you can also put in variables (unknown values; this should sound familiar) to make the equation more interesting. Variables are usually written as letters. For instance, we could write 2+X=7. We know the left side of the equation (2+X) must be the same as the right (7), so we can kinda figure out that the "unknown" value is actually 5. Remember, mathematical variables are just placeholders for numbers (pretty much like they are in code). Function equations are written like so:
f(x)=(transformation of x)
where f(x) is "function of x" and x is the input (value given to a function) to be transformed. "Transformation of x" is just some math to apply to x. Remember, functions are just a way to transform numbers. So let's say that our transformation is simply to double the number. Our mathematical function would look like:
f(x)=2*x
Now remember, f() is the function, so we can write f(10) to say "apply the function to 10". Here's what it would look like:
f(x) =2*x   'The function equation
f(10)=2*10  'Notice we replaced all x's with our "input"
f(10)=20    'This is the answer
That's really all a function is. You plug in a number and it spits out another one. A function can also take more than 1 input; for instance, you may be familiar with the distance formula (used to find the distance between two points, (x1,y1) and (x2,y2)): f(x1, y1, x2, y2) = √((x2 - x1)2 + (y2 - y1)2) This may look complicated if you've never seen it before, but all we have to do is plug in 4 actual numbers to the equation and we'll get one final number (in this case, the distance). This is another important point: functions can have many inputs but ONLY one output. It transforms a number (or multiple numbers) into a new number.

Functions practice

OK, let's try to come up with math functions ourselves. I'll describe what I want and you should try to come up with the function equation. Try to come up with the equation without looking at the answer (otherwise it's kinda useless). Here we go: A function to square a number; ie 5 becomes 25
answerf(x) = x2
A function to add 3 to a number; ie 5 becomes 8
answerf(x) = x + 3
A function which doubles a number and adds 1; ie 5 becomes 11
answerf(x) = 2 * x + 1
A function to compute the sin of a number
answerf(x) = sin(x)
Anyway, if you feel like my explanation of functions doesn't make sense, this website explains it more thoroughly and may be easier to understand: https://www.mathsisfun.com/sets/function.html

Programming Functions

SmileBASIC Built-ins

Functions in programming work in almost the same way: you give the function some inputs and it returns a single number (thus transforming input to output). However, unlike math functions, programming functions can do anything you want since it's actually just running code to compute the return value. So really, a programming function is an isolated, reusable block of code that accepts inputs and (may) return a value when finished. Let's take a look at some of the built-in functions for SmileBASIC:
SQR(X)      'Returns the square root of X
POW(X,E)    'Returns X raised to the E power
SIN(X)      'Returns the sin of X (where X is in radians)
COS(X)      'Returns the cos of X (where X is in radians)
PI()        'Returns the value of PI (always 3.14159 etc...)
RND(X)      'Returns a random number from 0 to X-1
Notice here that some functions don't have any inputs. Functions in programming aren't bound by the same rules as mathematical functions; they don't HAVE to have an input and furthermore, they don't even need to produce the same output for the same input. For instance, that RND function returns a different value every time, even though we keep passing in the same value for X. And here's how you might call (pass the input value(s) and retrieve the output value from) some of these functions:
PRINT SQR(25)       'Prints 5
PRINT POW(2,5)      'Prints 32 (2 to the power of 5)
PRINT SIN(PI()/2)   'Prints 1
PRINT RND(10)       'Prints some random number from 0 to 9
Notice here that we can give functions and equations as inputs (as with the SIN example). In programming, the parameters (inputs) are evaluated (computed/reduced to a single number) before the function is called. Before SIN is called, it has to know what PI()/2 is, so it evaluates that first then passes the computed value (1.571) to SIN.

SmileBASIC Silliness

Programming functions don't HAVE to return values, actually. This is true in any language; a function can simply be a piece of code that runs and then... that's it. For instance, PRINT is a function that accepts inputs (strings and stuff to display on the screen) but it doesn't return anything. In code, you can't do:
DIM A = PRINT "THING"  'this doesn't work
You'd get a syntax error because PRINT doesn't produce a value like the functions SQR or SIN do. Same with some other stuff we've used before like INPUT: it's only running code; it doesn't give back anything when you call it. In nearly all other programming languages, there is no distinction between functions that return values and functions that do not. They are written the same, called the same... they are EXACTLY the same. However, SmileBASIC is SSSSPEEEEESHHHHULLLL. Functions that return values include the parenthesis, like:
'These are standard functions which return values
DIM A=SQR(5)
DIM B=POW(4,2)
Functions that do NOT return values do NOT have parenthesis and will fail if you use them, like:
'These functions don't return values and thus don't use parenthesis
PRINT "HELLO"
INPUT "GIVE ME NUMBER";N

Functions in the SB Manual

There are many more functions built-in to SmileBASIC; we'll go over a few more in later lessons, or you can look them up in the SmileBASIC manual. The manual explains how to call the function and what parameters it expects. You can also press the ? button in the upper-right corner of the keyboard when the top screen cursor is on a function name to get information on that function. For instance, open up a program, type SQR , then press the ? in the upper-right corner of the keyboard to see information about that function. The top line shows how to use the function (Variable=SQR(Num)), and the rest explain the function and its parameters. If you find yourself confused about a function we use in the future, try looking it up in the manual while writing your program. Sometimes you'l look up a function and the manual will show weird stuff. For instance, type RND and bring up the in-game help (the question mark thing). The line that shows how to use the function looks something like
Variable=RND([Seed,] Max)
When a parameter is surrounded by square brackets, it's an optional parameter. Just like it sounds, optional parameters don't HAVE to be passed to a function. In the case of RND, you can call it like RND(5) and 5 will be the "max" parameter, or you can call it like RND(123,7) with 123 being the "seed" and 7 being the "max". Now look up PRINT in the in-game manual; it should look something like
PRINT [Expression [; or, Expression...]]
This one is a little uglier but don't worry, it's not that bad. Remember, things inside square brackets are optional, so since the entire parameter list of PRINT is within square brackets, you can call PRINT by itself and it'll still work (it'll just print an empty line). "Expression" means you can put basically anything there that produces a value, like 5+5, SQR(49), "MONKEYS", etc. Then we have ANOTHER set of square brackets inside the outer ones with "; or,", another Expression, and then an ellipsis (...). The ellipsis means you can repeat whatever is inside the square brackets as many times as you want, and the "; or," means each expression is separated by semicolons or commas. So, this means PRINT can take 0 or more expressions with each expression separated by semicolons or commas. Here's some examples:
PRINT
PRINT "Hello World"
PRINT "First","Second"
PRINT 55;"apples"
PRINT B$,"things";4*8
You may also see some functions with they keyword OUT in the call. Sometimes, a function just HAS to produce more than one value. In this case, instead of calling the function like V=FUNC(X), you'd do something more like FUNC(X) OUT V. This way, the function can produce more than one value. An example is retrieving the X and Y position of a sprite:
SPOFS I OUT X,Y
Don't worry, you don't need to know how sprites work yet. This function just needs to return both the X AND the Y position of a sprite, so this function uses OUT to return two values (stored into variables called X and Y, which can be named anything of course). Also, don't worry so much about OUT parameters right now; we won't be using them very much right now, and when we do I'll explain them again. Most of the things you use in SmileBASIC are functions, like XSCREEN, ACLS, SPDEF, etc. If you just keep in mind how to use functions and remember to use the in-game manual, you can write SmileBASIC code pretty easily! You just have to... you know... know what the functions actually do.

Conclusion

Mathematical functions are a way of transforming one or more numbers into another single number. They are written as equations, for example: f(x) = x2 (a function which squares inputs: 3 becomes 9, 7 becomes 49, etc). Programming functions are about the same as math functions: they receive inputs (parameters) and may produce an output value (return value). SmileBASIC built-in functions like SQR and POW are like math functions in that they have a list of inputs and produce a single output value, but other built-ins like PRINT and INPUT do not return any values and simply perform some task. Within programming functions are just little pieces of isolated code that can be reused to perform tasks. We only use (not alter) built-ins like SQR and PRINT because we can't see their inner code, but in a later lesson we'll learn to write our own functions to extend the functionality of SmileBASIC. There are no "do it yourself" examples here because the next lesson will be all about using what we've learned to actually make something! If I don't make it in a reasonable amount of time, just keep bugging me until I do lol. Next tutorial (part 9)

PRINT and INPUT are technically keywords, not functions without a return value, since they don't use standard syntax. EDIT: also PI() is a constant not a function

Replying to:12Me21
PRINT and INPUT are technically keywords, not functions without a return value, since they don't use standard syntax. EDIT: also PI() is a constant not a function
Underneath they are most certainly implemented as functions, however. A keyword is a syntax built-in that determines program flow and only has meaning in the language. A function is something which performs an action. Keywords do not perform actions; WHILE, IF, FOR, etc. do not do these things. PRINT, INPUT on the other hand basically HAVE to jump into a subroutine and ONLY have meaning as a command. I don't really care about how stupid SmileBoom is, I care about teaching people programming. In any other programming language, the way PRINT and INPUT work in BASIC would make them functions. Remember, this is How To Program, not How to use SmileBASIC.

Yaaaaaaaaaay thanks random!!! A big tutorial too~ :D

Replying to:12Me21
PRINT and INPUT are technically keywords, not functions without a return value, since they don't use standard syntax. EDIT: also PI() is a constant not a function
He's technically correct, but you actually did a pretty good job making the distinction anyway. Makes sense to me when I read it. It's worth noting that some languages return a null value for functions that return nothing, or something. Also, I'm pretty sure print was a keyword until Python 3... I don't get it either.

Replying to:12Me21
PRINT and INPUT are technically keywords, not functions without a return value, since they don't use standard syntax. EDIT: also PI() is a constant not a function
I mean yeah 12me is totally right. PRINT and INPUT are considered keywords in SmileBASIC (they're even highlighted as such). However, I haven't gone over any of the "proper" functions that don't return values in SmileBASIC and I'd rather use something that they should be familiar with from a previous lesson to show the difference. The way print and input work is exactly like a function with no return values, so... IDK.

Replying to:12Me21
PRINT and INPUT are technically keywords, not functions without a return value, since they don't use standard syntax. EDIT: also PI() is a constant not a function
Using keywords for things that produce no return value but have side effects is a very BASIC idiom, so it doesn't exactly surprise me. But PRINT undoubtedly has some call chain in there somewhere, so I don't know. We can't CALL any of these "keywords" either. There's also a goofy parsing ambiguity where you CAN use parens on keywords sometimes, but you never should. I bet you can figure out why:
PRINT("LOL AMBIGUOUS")

Replying to:12Me21
PRINT and INPUT are technically keywords, not functions without a return value, since they don't use standard syntax. EDIT: also PI() is a constant not a function
Even worse:
?SQR    (2)

Replying to:12Me21
PRINT and INPUT are technically keywords, not functions without a return value, since they don't use standard syntax. EDIT: also PI() is a constant not a function
Even, even worse:
FOR(i)=0to 1STEP 1
(a)=i
NEXT(i)
Totally legal syntax.

Replying to:12Me21
PRINT and INPUT are technically keywords, not functions without a return value, since they don't use standard syntax. EDIT: also PI() is a constant not a function
FOR TO=TO TO TO STEP STEP
 STEP=STEP
NEXT TO

Replying to:12Me21
PRINT and INPUT are technically keywords, not functions without a return value, since they don't use standard syntax. EDIT: also PI() is a constant not a function
Lmao that can't be legal, can it? I thought SmileBASIC reserved those phrases

Replying to:12Me21
PRINT and INPUT are technically keywords, not functions without a return value, since they don't use standard syntax. EDIT: also PI() is a constant not a function
TO and STEP aren't reserved, since they're only used in FOR, so they aren't ambiguous. neither are builtin function names:
COLOR=3
but keywords are:
NEXT=3 'not allowed
TO and STEP aren't normal keywords; they weren't even highlighted at first.

Replying to:12Me21
PRINT and INPUT are technically keywords, not functions without a return value, since they don't use standard syntax. EDIT: also PI() is a constant not a function
Huh, interesting. I've always voided those phrases which highlight themselves like that.

Replying to:12Me21
PRINT and INPUT are technically keywords, not functions without a return value, since they don't use standard syntax. EDIT: also PI() is a constant not a function
ITT: parsing ambiguities in general.

The first argument to RND isn't the seed, it's which RNG to use. There are 8 of them, and each one can have its own seed, which is set by RANDOMIZE.

Hey buddy, you think you can work on that next/last tutorial?

Replying to:Defaultio
Hey buddy, you think you can work on that next/last tutorial?
Oh jeez it's been 3 months? OK um... I'll try to do it soon.

Replying to:Defaultio
Hey buddy, you think you can work on that next/last tutorial?
soon

Replying to:Defaultio
Hey buddy, you think you can work on that next/last tutorial?
I... I'm terrible. I'm sorry!

Replying to:Defaultio
Hey buddy, you think you can work on that next/last tutorial?
Naw it's fine, but I do think you should make #9 ehhh sometime this week. 1-8 have been very helpful so I'm pumped for #9

Ok you shouldn't, and I mean SHOULDN'T mix up math and programming. That's the best way to confuse beginners. For example: Algebra. Functions in code are used when you wish to set a side code that can be reused again and again. For example:
DEF ADDITION NUMBER1,NUMBER2
   RETURN NUMBER1 + NUMBER2
END

' Calling the function
ANSWER = ADDITION 5,5
PRINT ANSWER 
This is more understandable and straight to the point. The functions that you brought out were built in to help reduce time and energy on writing math calculations. It's very important to keep things simple. You're going a little off topic here.