alexanderson
alexanderson

Reputation: 139

Arraysort f# not giving wanted type

I've created a function that sorts an array by converting it to a list first (might be a little silly, but that's my solution whatsoever). Anyways, it doesn't show up with the type like other similar sort functions does. I'd like it to look like sort : (’a [] -> ’a []) when ’a : comparison. Mine goes:

val arraySort : array:int [] -> int []
val it : unit = ()

Upvotes: 1

Views: 52

Answers (1)

Sehnsucht
Sehnsucht

Reputation: 5049

First step, remove all type annotation ; you normally put it only when needed (ie when inference can't determine things without a little help) Second step use function inside module (here Array module) that way (among other things) inference can determine what is the array using the signature of those functions

That gives :

let rec putNumber (thelist, value) =
  match thelist with
  | [] -> [value]
  | x :: xs -> if value <= x
               then [value; x] @ xs
               else x :: putNumber (xs, value)

let sort array =
  let rec sortList array blist index =
    let clist = putNumber (blist, Array.get array index)
    if index < Array.length array - 1
    then sortList array clist (index + 1)
    else clist
  List.toArray (sortList array [] 0)

That said, without changing the algorithm (although it's not really efficient) things can be written a little more idiomatically :

let rec putNumber value = function
  | []                      -> [value]
  | x :: xs when value <= x -> [value; x] @ xs
  | x :: xs                 -> x :: putNumber value xs

let sort array =
  let len = Array.length array

  let rec sortList blist index =
    let value = Array.get array index
    let clist = putNumber value blist

    if index < len - 1
    then sortList clist (index + 1)
    else clist

  sortList [] 0
  |> List.toArray

Upvotes: 3

Related Questions