Home > Software engineering >  F# int list versus unit list
F# int list versus unit list

Time:11-23

open System

let rec quick (cast: int list) mmm =
    match mmm with
    | [] -> []
    | first::rest ->
    
        let small = (rest |> List.filter (fun x -> x < first)) 
        let large = (rest |> List.filter (fun x -> x >= first))

        quick small |> ignore
        quick large |> ignore
    
        //[small @ [first] @ large]
        List.concat [small; [first]; large]

[<EntryPoint>]
let main argv =
    printfn "%A" (quick [3;5;6;7;8;7;5;4;3;4;5;6]);;

0

Trying to implement a simple quicksort function in F#. Relatively new to the language, but by all account from what I've read and my understanding of the syntax this should present an integer list but is instead presenting the ambiguous "unit list".

Why does this give a unit list and not an int list?

It errors out at "%A" saying the types do not match.

CodePudding user response:

As given in the OP, quick is a function that takes two parameters: cast and mmm. The type of the function is int list -> int list -> int list.

The function call quick [3;5;6;7;8;7;5;4;3;4;5;6], however, only supplies one argument. Since F# functions are curried, the return value is a new function:

> quick [3;5;6;7;8;7;5;4;3;4;5;6];;
val it : (int list -> int list) = <fun:it@3-4>

This function (in my F# Interactive window called it@3-4) has the type int list -> int list - that is: It's a function that 'still waits' for an int list argument before it runs.

When you print it with the %A format specifier, it prints <fun:it@4-5> to the console. The return value of printfn is () (unit):

> printfn "%A" (quick [3;5;6;7;8;7;5;4;3;4;5;6]);;
<fun:it@4-5>
val it : unit = ()

You probably only want the function to take a single list parameter. Additionally, the steps you ignore are having no effect, so you might consider another way to recursively call quick.

  • Related