FUNZIONI

Qui andiamo a conoscere le funzioni!.
La possibilità di definire delle funzioni permette innanzitutto di stenografare frammenti di codice, in modo tale da 'copiare' un frammento in parti diverse del codice senza ricopiarlo interamente, ma semplicemente richiamando la funzione che esegue quel codice. In questi casi le funzioni sono solo abbreviazioni, che rendono il codice di più facile scrittura e lettura, ma non aggiungono nessuna nuova funzionalità.
Esiste però una modalità di definizione di una funzione che estende le funzionalità eseguibili dai nostri linguaggi:
la definizione per ricorsione.
Della ricorsione diamo un esempio, per ognuno dei linguaggi qui considerati, rinviando a dei buoni tutorial per ulteriori spiegazioni e motivazioni.

ATTENZIONE: la ricorsione è importante!

PHP

Funzione

echo '<form action="function.php#tbox1" method="post">
<input type="text"  name="numOne" value="'.($_POST['numOne']?$_POST['numOne']:"Scrivi un numero").'">
<input type="text"  name="numTwo" value="'.($_POST['numTwo']?$_POST['numTwo']:"Scrivi un numero").'">
<input type="submit"  value="Invia" >
</form>';

function  test($parOne, $parTwo){

if(is_numeric($parOne) && is_numeric($parTwo)){$sum=$parOne+$parTwo;  $string = 'la somma dei due numeri &egrave;: '.$sum;}else{$string = 'Pls. inserisci due numeri!';}

	return $string; 
}

echo test($_POST['numOne'], $_POST['numTwo']);

Pls. inserisci due numeri!
User-defined function
PHP user-defined function


definizione per recursione  click: vedi codice

$folderPath = "../step_prog";
function readFolder( $path ) {
 
  // Open the folder
  if ( !( $dir = opendir( $path ) ) ) die( "Can't open $path" );
  $filenames = array();
 
  // Read the contents of the folder, ignoring '.' and '..', and
  // appending '/' to any subfolder names. Add all the files and
  // subfolders to the $filenames array.
 
  while ( $filename = readdir( $dir ) ) {
    if ( $filename != '.' && $filename != '..' ) {
      if ( is_dir( "$path/$filename" ) ) $filename .= '/';
      $filenames[] = $filename;
    }
  }
 
  closedir ( $dir );
 
  // Sort the filenames in alphabetical order
  sort( $filenames );
 
  // Display the filenames, and process any subfolders
  $string = '';
  $string .=  "<ul>";
 
  foreach ( $filenames as $filename ) {
    $string .=  "<li>". $filename;
    if ( substr( $filename, -1 ) == '/' ){$string .=' '.  readFolder( $path."/" . substr( $filename, 0, -1 ) );}
    $string .=  "</li>";
  }
 
  $string .=  "</ul>";

  return $string; 
}
echo "<h2>file e cartelle in  ".$folderPath.":</h2>";
echo readFolder( $folderPath );

file e cartelle in ../step_prog:

mostro il contenuto della cartella, e delle cartelle ivi contenute il loro contenuto, e se tra queste ultime vi sono cartelle, il loro contenuto, e così via ricorsivamente.
Nota: perché questa procedura non va all'infinito?
---------------
  • array.php
  • basics.php
  • code.php
  • code.txt
  • code_factorial.php
  • code_readFolder.php
  • default.css
  • espressioni.php
  • font.css
  • fonts.css
  • fonts/
    • FontAwesome.otf
    • fontawesome-social-webfont.eot
    • fontawesome-social-webfont.svg
    • fontawesome-social-webfont.ttf
    • fontawesome-social-webfont.woff
    • fontawesome-webfont.eot
    • fontawesome-webfont.svg
    • fontawesome-webfont.ttf
    • fontawesome-webfont.woff
  • footer.php
  • footer.php~
  • function.php
  • highlight/
    • CHANGES.md
    • LICENSE
    • README.md
    • README.ru.md
    • highlight.pack.js
    • styles/
      • agate.css
      • androidstudio.css
      • arduino-light.css
      • arta.css
      • ascetic.css
      • atelier-cave-dark.css
      • atelier-cave-light.css
      • atelier-dune-dark.css
      • atelier-dune-light.css
      • atelier-estuary-dark.css
      • atelier-estuary-light.css
      • atelier-forest-dark.css
      • atelier-forest-light.css
      • atelier-heath-dark.css
      • atelier-heath-light.css
      • atelier-lakeside-dark.css
      • atelier-lakeside-light.css
      • atelier-plateau-dark.css
      • atelier-plateau-light.css
      • atelier-savanna-dark.css
      • atelier-savanna-light.css
      • atelier-seaside-dark.css
      • atelier-seaside-light.css
      • atelier-sulphurpool-dark.css
      • atelier-sulphurpool-light.css
      • atom-one-dark.css
      • atom-one-light.css
      • brown-paper.css
      • brown-papersq.png
      • codepen-embed.css
      • color-brewer.css
      • darcula.css
      • dark.css
      • darkula.css
      • default.css
      • docco.css
      • dracula.css
      • far.css
      • foundation.css
      • github-gist.css
      • github.css
      • googlecode.css
      • grayscale.css
      • gruvbox-dark.css
      • gruvbox-light.css
      • hopscotch.css
      • hybrid.css
      • idea.css
      • ir-black.css
      • kimbie.dark.css
      • kimbie.light.css
      • magula.css
      • mono-blue.css
      • monokai-sublime.css
      • monokai.css
      • obsidian.css
      • ocean.css
      • paraiso-dark.css
      • paraiso-light.css
      • pojoaque.css
      • pojoaque.jpg
      • purebasic.css
      • qtcreator_dark.css
      • qtcreator_light.css
      • railscasts.css
      • rainbow.css
      • routeros.css
      • school-book.css
      • school-book.png
      • solarized-dark.css
      • solarized-light.css
      • sunburst.css
      • tomorrow-night-blue.css
      • tomorrow-night-bright.css
      • tomorrow-night-eighties.css
      • tomorrow-night.css
      • tomorrow.css
      • vs.css
      • vs2015.css
      • xcode.css
      • xt256.css
      • zenburn.css
  • if.php
  • if.php~
  • images/
    • 82427-letter-and-envelope.jpg
    • Brendan_Eich_Mozilla_Foundation_official_photo.jpg
    • Rasmus_Lerdorf_August_2014_(cropped).JPG
    • overlay.png
    • screenshot-developer.mozilla.org-2018-03-13-18-07-36.jpg
    • screenshot-developer.mozilla.org-2018-03-13-18-08-20.jpg
    • screenshot-developer.mozilla.org-2018-03-26-17-23-54.jpg
    • screenshot-developer.mozilla.org-2018-03-26-19-56-14.png
    • screenshot-developer.mozilla.org-2018-03-26-20-00-55.jpg
    • screenshot-en.wikipedia.org-2018-03-26-16-58-57.jpg
    • screenshot-en.wikipedia.org-2018-03-26-16-59-35.jpg
    • screenshot-p5js.org-2018-03-26-20-04-18.jpg
    • screenshot-php.net-2018-03-13-18-10-12.jpg
    • screenshot-php.net-2018-03-27-13-53-55.jpg
    • screenshot-processing.org-2018-03-13-18-08-42.jpg
    • screenshot-processing.org-2018-03-13-18-09-09.jpg
    • screenshot-tisch.nyu.edu-2018-05-01-19-43-46.png
  • index.php
  • mario.css
  • math.php
  • menu.php
  • oggetti.php
  • p5.zip
  • p5/
    • p5.js
    • p5/
      • addons/
        • p5.dom.js
        • p5.dom.min.js
        • p5.sound.js
        • p5.sound.min.js
      • empty-example/
        • index.html
        • sketch.js
      • p5.js
      • p5.min.js
      • sketch.js
  • sketch.js
  • testFunction.php
  • testWalkDOM.php
  • tipididati.php
  • var.php

ricorsione: un classico esempio: il fattoriale  click: vedi codice

 
function factorialString($n){
	$out = 0; 
        $comp = '';
	$string = ''; 
if ($n == 0) {
	$out = 1;
	$comp = 1; 
	$string = "caso base: <br> 0. factorial(0)  =  1, risultato &egrave; 1<br>";
}else{
  	$call = $n-1; 
        $out = ($n * (factorialString($call)[0]));
        $comp = $n . '*' . factorialString($call)[1];
 
        $string = factorialString($call)[2] .$n.". factorial(".$n.") =  ".$n." * factorial(".$call.") = ". factorialString($call)[1].", risultato &egrave; ".$out."<br>";
        
}
  $r = array($out,$comp,$string);
  return $r;
}
echo factorialString(11)[2];

caso base:
0. factorial(0) = 1, risultato è 1
1. factorial(1) = 1 * factorial(0) = 1, risultato è 1
2. factorial(2) = 2 * factorial(1) = 1*1, risultato è 2
3. factorial(3) = 3 * factorial(2) = 2*1*1, risultato è 6
4. factorial(4) = 4 * factorial(3) = 3*2*1*1, risultato è 24
5. factorial(5) = 5 * factorial(4) = 4*3*2*1*1, risultato è 120
6. factorial(6) = 6 * factorial(5) = 5*4*3*2*1*1, risultato è 720
google about it!

JS

Traverse DOM elements recursively -
Click qui (Attento, lungo!)

var walkDom=function(html_elem, func)
{
	if(typeof func!='function') return;
	var loop=function(html_elem)
	{
		do
		{
			func(html_elem); // call callback for every element
			if(html_elem.hasChildNodes())
				loop(html_elem.firstChild);
		}while(html_elem=html_elem.nextSibling);
	};
	loop(html_elem);
	//loop(html_elem.firstChild); // do not include siblings of start element
}
var fn=function(html_elem)
{
	alert(html_elem.outerHTML);
}

da trovare



Processing

Funzione ricorsiva - Frattale

float theta; 
float a = 0;

void setup() {
  size(640, 360);
}

void draw() {
  background(255);
  frameRate(3);
  stroke(240,0,0);
  // Let's pick an angle 0 to 90 degrees based on the mouse position
  if (a < 360){ a = a+5; 
	}else{ a=0; }
  // Convert it to radians
  theta = radians(a);
  // Start the tree from the bottom of the screen
  translate(width/2,height);
  // Draw a line 120 pixels
  line(0,0,0,-100);
  // Move to the end of that line
  translate(0,-100);
  // Start the recursive branching!
  branch(100);
}

void branch(float h) {
  // Each branch will be 2/3rds the size of the previous one
  h *= 0.66;
  // All recursive functions must have an exit condition!!!!
  // Here, ours is when the length of the branch is 2 pixels or less
  if (h > 2) {
    pushMatrix();    // Save the current state of transformation (i.e. where are we now)
    rotate(theta);   // Rotate by theta
    line(0, 0, 0, -h);  // Draw the branch
    translate(0, -h); // Move to the end of the branch
    branch(h);       // Ok, now call myself to draw two new branches!!
    popMatrix();     // Whenever we get back here, we "pop" in order to restore the previous matrix state
    
    // Repeat the same thing, only branch off to the "left" this time!
    pushMatrix();
    rotate(-theta);
    line(0, 0, 0, -h);
    translate(0, -h);
    branch(h);
    popMatrix();
  }
}


Processing
Frattali e Ricorsione (NICE!)



PHP

PHP is a server-side scripting language designed for web development but also used .....

wikipedia

JS

JavaScript ("JS" for short) is a full-fledged dynamic programming language that, when applied to an HTML document, can provide dynamic interactivity on websites. It was invented by Brendan Eich, co-founder of the Mozilla project, the Mozilla Foundation, and the Mozilla Corporation. JavaScript is incredibly versatile. You can start small, with carousels, image galleries, fluctuating layouts, and responses to button clicks. With more experience, you'll be able to create games, animated 2D and 3D graphics, comprehensive database-driven apps, and much more!.....

MDN JavaScript basics

Brendan Eich

wikipedia

p5.js

Hello! p5.js is a JavaScript library that starts with the original goal of Processing, to make coding accessible for artists, designers, educators, and beginners, and reinterprets this for today's web.

p5.js
<