Sha256: 7508ee47387b252d9ecd2e25d8ab9c56de188f5474ff8a8937f3aa4f9292fac2

Contents?: true

Size: 1.05 KB

Versions: 54

Compression:

Stored size: 1.05 KB

Contents

exception EmptyList
datatype 'a lazylist = Nil | Cons of ('a * (unit -> 'a lazylist));
fun next s = let
    fun next' Nil = raise EmptyList
      | next' (Cons(a,f)) = f()
in
    next' s
end ;

fun hd s = let
    fun hd' Nil = raise EmptyList
      | hd' (Cons(a, _)) = a
in
    hd' s
end ;

fun allPrimes n = let
    fun isPrime n = let
        fun factors n = let
            fun factors' 0 acc = acc
              | factors' c acc = if (n mod c) = 0
                                 then factors' (c-1) (c :: acc)
                                 else factors' (c-1) acc
        in
            factors' (n div 2) []
        end
    in
        (List.length (factors n)) = 1
    end

    fun nextPrime n = let
        val nextN = if (n mod 2) = 0 then n + 1 else n + 2
    in
        if isPrime nextN then nextN else nextPrime nextN
    end

in
    Cons(n, fn () => (allPrimes (nextPrime n)))
end ;

fun nthPrime n = let
    fun nthPrime' 0 s = hd s
      | nthPrime' n s = nthPrime' (n-1) (next s)
in
    if n <= 0 then raise Domain
    else nthPrime' (n-1) (allPrimes 2)
end ;

Version data entries

54 entries across 54 versions & 1 rubygems

Version Path
trackler-2.2.1.44 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.43 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.42 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.41 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.40 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.39 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.38 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.37 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.36 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.35 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.34 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.33 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.32 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.31 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.30 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.29 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.28 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.27 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.26 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.25 tracks/sml/exercises/nth-prime/example.sml