03.12.2012 Views

Tema 2: Características de la programación funcional

Tema 2: Características de la programación funcional

Tema 2: Características de la programación funcional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Tema</strong> 2: <strong>Características</strong> <strong>de</strong> <strong>la</strong> <strong>programación</strong> <strong>funcional</strong><br />

el i<strong>de</strong>ntificador que está ligado al procedimiento.<br />

Una función pue<strong>de</strong> ser el argumento <strong>de</strong> otra función.<br />

Por ejemplo, po<strong>de</strong>mos <strong>de</strong>fnir <strong>la</strong> siguiente función aplicar que toma como argumento una<br />

función f 2 argumentos y realiza <strong>la</strong> l<strong>la</strong>mada a f con los 2 argumentos:<br />

(<strong>de</strong>fine (aplicar f x y)<br />

(f x y))<br />

> (aplicar + 2 3)<br />

5<br />

> (aplicar * 2 3)<br />

6<br />

(aplicar word 'ho<strong>la</strong> 'adios)<br />

ho<strong>la</strong>adios<br />

En el siguiente ejemplo <strong>de</strong>finimos una función que toma dos procedimientos unarios (<strong>de</strong> un<br />

argumento) f y g y los aplica a un número:<br />

(<strong>de</strong>fine (aplicar-2 f g x)<br />

(f (g x)))<br />

(<strong>de</strong>fine (5+ x)<br />

(+ 5 x))<br />

(<strong>de</strong>fine (doble x)<br />

(* 2 x))<br />

> (aplicar-2 5+ doble 8)<br />

21<br />

Una función pue<strong>de</strong> ser el valor <strong>de</strong>vuelto por otra función.<br />

Vamos a <strong>de</strong>finir una función que <strong>de</strong>vuelve otra función. La siguiente función<br />

hacer-suma1 <strong>de</strong>fine en su interior <strong>la</strong> función suma1 y <strong>la</strong> <strong>de</strong>vuelve.<br />

(<strong>de</strong>fine (hacer-suma1)<br />

(<strong>de</strong>fine (suma1 x)<br />

(+ x 1))<br />

suma1)<br />

(<strong>de</strong>fine f (hacer-suma1))<br />

> (f 3)<br />

4<br />

Vemos que el resultado <strong>de</strong> <strong>la</strong> l<strong>la</strong>mada a hacer-suma1 se guarda en <strong>la</strong> variable f y <strong>de</strong>spués<br />

comprobamos que realmente es una función que suma 1.<br />

Po<strong>de</strong>mos complicar un poco más el ejemplo <strong>de</strong>finiendo un parámetro con el número que<br />

queremos sumar en <strong>la</strong> función que <strong>de</strong>volvemos. Así, <strong>la</strong> función hacer-sumak construye<br />

otra función que suma el parámetro k al argumento x que se le pasa:<br />

(<strong>de</strong>fine (hacer-sumak k)<br />

(<strong>de</strong>fine (sumak x)<br />

Page 13<br />

Copyright © 2006 Depto. CCIA, Universidad <strong>de</strong> Alicante All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!