Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.forth > #21647
| From | "WJ" <w_a_x_man@yahoo.com> |
|---|---|
| Newsgroups | comp.lang.forth |
| Subject | Re: Sum of squares |
| Date | 2013-04-13 17:34 +0000 |
| Organization | A noiseless patient Spider |
| Message-ID | <kkc4v7$dk0$1@dont-email.me> (permalink) |
| References | <10851509008435@frunobulax.edu> |
Marcel Hendrix wrote:
> Admit it (when trying it yourself), this exercise is
> surprisingly tricky.
>
> -marcel
>
> -- -------------------------------------------
> (*
> * LANGUAGE : ANS Forth with extensions
> * PROJECT : Forth Environments
> * DESCRIPTION : Sum of squares of two largest of three values
> * CATEGORY : Programming exercise
> * AUTHOR : Marcel Hendrix
> * LAST CHANGE : March 25, 2012, Marcel Hendrix
> *)
>
>
>
> NEEDS -miscutil
>
> REVISION -sumsquares "--- Sum of Squares Version 0.01 ---"
>
> PRIVATES
>
> DOC
> (*
>
> Sum of squares of two largest of three values
>
> This exercise comes to us from the book "Structure and Interpretation of
> Computer Programs" by Abelson and Sussman (exercise 1.3):
>
> Define a procedure that takes three numbers as arguments and returns
> the sum of the squares of the two larger numbers.
> *)
> ENDDOC
>
> : DSQR ( u -- du ) DUP M* ; PRIVATE
> : .ANSWER ( ud -- ) CR ." The sum of the squares of the two larger numbers is " (n,3) ; PRIVATE
>
> : SOS ( n1 n2 n3 -- )
> 2DUP > IF SWAP ENDIF ( x1) DSQR 2>R
> MAX ( x2) DSQR 2R> D+ .ANSWER ;
>
>
> : SQR ( u1 -- u2 ) DUP * ; PRIVATE
> : SUM-OF-SQUARES ( n1 n2 n3 -- ) 2DUP > IF SWAP ENDIF SQR -ROT MAX SQR + . ;
>
> :ABOUT CR ." Print the sum of the squares of the two larger numbers from {n1, n2, n3}."
> CR ." The numbers should have less than 18 digits."
> CR ." Try: 1 2 3 SOS -- print 13, double precision."
> CR ." 1 2 3 SUM-OF-SQUARES -- single precision." ;
>
> .ABOUT -sumsquares CR
> DEPRIVE
>
> (* End of Source *)
Factor:
: sos ( a b c -- x )
3array [ <=> ] sort 2 tail* [ dup * ] map first2 + ;
1 2 3 sos .
13
10 2 3 sos .
109
Back to comp.lang.forth | Previous | Next — Next in thread | Find similar
Re: Sum of squares "WJ" <w_a_x_man@yahoo.com> - 2013-04-13 17:34 +0000 Re: Sum of squares Sieur de Bienville <morrimichael@gmail.com> - 2013-04-13 11:43 -0700
csiph-web