Sha256: c6d0a2050b857b79ef8c62d3d7d63ae776c7e038cd64b9191b475adda9495daf

Contents?: true

Size: 1.11 KB

Versions: 196

Compression:

Stored size: 1.11 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
    nthPrime' (n-1) (allPrimes 2)
end ;

Version data entries

196 entries across 196 versions & 1 rubygems

Version Path
trackler-2.0.8.48 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.47 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.46 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.45 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.44 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.43 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.42 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.41 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.40 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.39 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.38 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.37 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.36 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.35 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.34 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.33 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.32 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.31 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.30 tracks/sml/exercises/nth-prime/example.sml
trackler-2.0.8.29 tracks/sml/exercises/nth-prime/example.sml