1

I'm recently new to F# so please bear with me. The problem i have is I'm trying to find only prime numbers.

I've write this code:

  let isPrime n =
    let rec check i =
    i > n/2 || (n % i <> 0 && check (i + 1))
       check 2;;

let listNums = List.filter isPrime >> List.length;;

 let nums = [ 16; 17; 3; 4; 2; 5; 11; 6; 7; 18; 13; 14; ];;

let countPrimes (x:int) = x |> List.ofSeq |> listNums;;

trying to call

countPrimes nums;;

but this is failed with message:

The type 'int' is not compatible with the type 'seq<'a>'

any help would be appreciated

user3473445
  • 184
  • 5
  • 18

3 Answers3

2

I found the solution

let isPrime n =
let rec check i =
    i > n/2 || (n % i <> 0 && check (i + 1))
check 2;;

let listNums = List.filter isPrime >> List.length;;

let nums = [| 16; 17; 3; 4; 2; 5; 11; 6; 7; 18; 13; 14; |];;

let countPrimes (x:int[]) = x |> List.ofSeq |> listNums;;

countPrimes nums;;

Thanks all!

user3473445
  • 184
  • 5
  • 18
1

x |> List.ofSeq

seems to be the problem to me. You are passing an int into a function that requires a list. List.toSeq changes a list into a sequence. You want the function countPrimes to take a List of integers, not simply an integer. Although Carsten is right, listNums already takes a List of integers (edit: and computes the value you want provided isPrime is correct).

cba
  • 11
  • 3
0

You do not need to countPrimes separately. Enough to remove and will work:

let isPrime n =
    let rec check i =
        i > n/2 || (n % i <> 0 && check (i + 1))
    check 2

let nums = [ 16; 17; 3; 4; 2; 5; 11; 6; 7; 18; 13; 14; ]

let listPrime lst =
    lst |> List.filter isPrime

nums |> listPrime |> printfn "%A"

Out: [17; 3; 2; 5; 11; 7; 13]

Link: https://dotnetfiddle.net/nVXwZ5

FoggyFinder
  • 2,230
  • 2
  • 20
  • 34