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.24 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.23 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.22 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.21 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.20 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.19 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.18 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.17 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.16 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.15 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.14 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.13 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.12 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.11 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.10 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.9 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.8 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.7 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.6 tracks/sml/exercises/nth-prime/example.sml
trackler-2.2.1.5 tracks/sml/exercises/nth-prime/example.sml