Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.forth > #24146

Re: Sum of squares

From "WJ" <w_a_x_man@yahoo.com>
Newsgroups comp.lang.forth
Subject Re: Sum of squares
Date 2013-07-04 10:17 +0000
Organization A noiseless patient Spider
Message-ID <kr3i3f$ie5$1@dont-email.me> (permalink)
References <10851509008435@frunobulax.edu> <kr2ile$h0a$1@dont-email.me>

Show all headers | View raw


WJ wrote:

> 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 *)
> 
> OCaml:
> 
> let rec sos a b c =
>   if a > b then (sos b a c)
>   else
>     if b > c then (sos a c b)
>     else b*b + c*c ;;
> 
> # sos 10 2 3;;
> - : int = 109

Clojure:

(defn sos [a b c]
  (if (> a b)
    (sos b a c)
    (if (> b c)
      (sos a c b)
      (+ (* b b) (* c c)))))


Another way:

(defn sos [a b c]
  (apply + (map #(* % %) (take-last 2 (sort (list a b c))))))

Back to comp.lang.forth | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Re: Sum of squares "WJ" <w_a_x_man@yahoo.com> - 2013-07-04 01:20 +0000
  Re: Sum of squares "WJ" <w_a_x_man@yahoo.com> - 2013-07-04 10:17 +0000
    Re: Sum of squares "WJ" <w_a_x_man@yahoo.com> - 2013-07-04 10:25 +0000

csiph-web