Functional programming

new topic     » topic index » view thread      » older message » newer message

Hello everyone,

I've been playing with mLite, a lightweight interpreter for the ML functional programming language.

One of the benefits of learning another language is that it forces you to think differently. So I'm now re-examining my earlier RosettaCode submissions and future Euphoria submissions in the light of the functional approach. Someone's already done Happy Numbers in Euphoria, but this is how it could be done in mLite:

local 
   fun get_digits  
         (d, s) where (d = 0) = s 
      |    (d, s) = get_digits( d div 10, (d mod 10) :: s) 
      |    n = get_digits( n div 10, [n mod 10] ) 
   ; 
   fun mem (x, []) = false 
      |    (x, a :: as) where (x = a) = true 
      |    (x, _ :: as) = mem (x, as) 
in 
   fun happy 
         1 = "happy" 
      |   n = 
            let  
               val this = (fold (+,0) ` map (fn n = n ^ 2) ` get_digits n); 
               val sads = [2, 4, 16, 37, 58, 89, 145, 42, 20] 
            in 
               if (mem (n,sads)) then 
                  "unhappy" 
               else 
                  happy this 
            end 
end 
; 
 
map (fn n = (print n; print " is "; println ` happy n)) ` iota 2000; 

Kind regards
Bruce / bugmagnet

new topic     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu