25.06.2013 Views

Il Linguaggio Fortran 90/95

Il Linguaggio Fortran 90/95

Il Linguaggio Fortran 90/95

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.

260 Unità di Programma<br />

INTEGER, INTENT(IN) :: x(:,:)<br />

INTEGER, INTENT(IN) :: cost<br />

INTEGER, DIMENSION(SIZE(x,1),SIZE(x,2)) :: array_func<br />

array_func(:,:) = x(:,:)*cost<br />

END FUNCTION array_func<br />

5.10 Funzioni stringa di caratteri<br />

In molti casi può essere utile definire una function che restituisca una stringa di caratteri di<br />

una data lunghezza. Detta lunghezza può, indifferentemente, essere fissa oppure dipendere da<br />

uno dei parametri formali. Per chiarire quanto detto, si guardi il seguente esempio in cui la<br />

function reverse acquisisce una stringa in input e la restituisce nella sua forma ”invertita”:<br />

FUNCTION reverse(parola)<br />

IMPLICIT NONE<br />

CHARACTER(LEN=*), INTENT(IN) :: parola<br />

CHARACTER(LEN=LEN(parola)) :: reverse<br />

INTEGER :: l, i<br />

l = LEN(parola)<br />

DO i=1,l<br />

reverse(l-1+1:l-i+1) = parola(i:i)<br />

END DO<br />

END FUNCTION reverse<br />

Si noti che la stringa parola non può essere usata fino a che non venga dichiarata: è per questa<br />

ragione che il tipo della funzione non può apparire come prefisso nella dichiarazione di funzione.<br />

In questo caso la lunghezza del risultato della funzione è determinata automaticamente pari a<br />

quella del parametro formale parola.<br />

Un esempio lievemente più complesso è il seguente:<br />

PROGRAM stringhe<br />

IMPLICIT NONE<br />

INTEGER, PARAMETER :: l=7<br />

CHARACTER(LEN=l) :: s1 = "Antonio"<br />

! start<br />

WRITE(*,*) func(2*l,s1)<br />

STOP<br />

CONTAINS<br />

FUNCTION func(n,b)<br />

INTEGER, PARAMETER :: k=3<br />

CHARACTER(LEN=*), INTENT(IN) :: b ! stringa di lunghezza fittizia<br />

INTEGER, INTENT(IN) :: n<br />

CHARACTER(LEN=2*LEN(b)) :: func ! stringa di lung. automatica<br />

CHARACTER(LEN=LEN(b)) :: y ! stringa locale di lung. automatica

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

Saved successfully!

Ooh no, something went wrong!