Perfect numbers in Python


SML is odd

(if exp1 then exp2 else exp3) div (if exp4 then exp5 else exp6)

Is valid and for at least some problems, is entirely reasonable.

I think the key to SML, at least so far… *everything* is an expression.  Any complete statement returns a value, and anything that returns a value counts as an expression.  Ok, small exceptions here and there like, well, exceptions, but approaching it with “everything is an expression” has really helped my understanding.

Project Euler problem 1- SML Implementation

Finished the current assignments and lectures for my Programming Languages course on Coursera, so I figured I’d go and do some other stuff in ML.  ML is a functional language, very heavy on recursion among other fun differences from imperative and OO languages.

Here’s a solution to Project Euler problem 1, summing all multiples of 3 and 5 that are below 1000.  

fun sum_multiples_3_5(limit : int) =

    if limit = 0

    then 0

    else if limit mod 3 = 0 orelse limit mod 5 = 0

           then limit + sum_multiples_3_5(limit-1)

           else sum_multiples_3_5(limit-1)

This is a general function, it will sum all multiples of 3 and 5 up through your limiting value.  If you want less than 1000, then, you’d call it:


The answer, in this case, is 233168.

I may generalize it further, taking a list of ints which are the factors you want multiples of.  That looks like a lot of extra work for something that is right now killing time because I can’t sleep, though, so I’ll be putting it off a bit.