Aaron
Aaron

Reputation: 21

having trouble using F# functions

I am new to F# and trying to learn how to use recursive function in F#. I am trying to play around with creating my own function and am having trouble getting it to work. What I have managed to do so far is get 10 random numbers and print them out. Both of those pieces of code I found online. I want to use the sort function(eventually it will be a sort function, but I am not asking for that) and am having trouble getting it to work. I put a // by where I think I am having trouble. I am not sure what this function will do, but as I wrote before I am just trying to play around with it

   let randomNumberList count =  
         let rnd = System.Random() 
         List.init count (fun numbers -> rnd.Next (1, 1000)) 

    let rec printList listx =
           match listx with
         | head :: tail -> printf "%d " head; printList tail
         | [] -> printfn ""

    let nonSortedList = randomNumberList 10

    printList nonSortedList

    let rec sort list =
        match list with
        | head :: tail -> sort tail
        | [] -> 0

   sort  nonSortedList//I want to send the norSorted list into the sort function

   printList nonSortedList//print out results after putting it into the sort function

Upvotes: 0

Views: 154

Answers (1)

Mongus Pong
Mongus Pong

Reputation: 11477

You aren't assigning the results of sort to anything.

As F# is (largely) a functional language, it strongly encourages you to use immutable data structures. That means your data never changes, it is just passed to functions which use the data to create new representations of that data.

So your sort function is not changing the order of the list, rather it should return a new list that represents the ordered representation of the passed in list.

As F# expects this behaviour, if you don't do anything with the results F# is clever enough to know that you are probably doing something stupid.

So you should go :

let orderedList = sort nonSortedList
printList orderedList 

If you really want to ignore the results - which sometimes you do, if your method has side effects and you are just calling it for its side effects - you can pass the results to ignore

sort nonSortedList |> ignore

Upvotes: 3

Related Questions