F # linked list using entries

I am trying to implement a linked list in f # using entries. I know that I can use the building as a list, but this is for training. My type:

type Cell = { data : int; next : RList} and RList = Cell option ref 

And I would like to make a simple insert function, but I was told that f # expects a boolean value, but it was offered an expression like unit. I am wondering if this means that I have formatted the if / else statement incorrectly

 let rec insert comp (item: int) (list: RList) = let c = {data = item; next = ref None} match !list with | None -> list = cellToRList c | Some {data = d; next = remaining} -> if (comp(item, d)) then c.next := !remaining remaining := ref c (* compiler indicates error here *) else insert comp item remaining 

Note: comp is any comparison function that accepts (item, d) as input and outputs true or false ex:

 let compare (x, y) = x > y 

My goal is simply to insert a new cell with data = element if we compare the outputs to true. In the above example, it can be used to insert into a sorted list and save the sort. The whole function should return a type block. Any hint as to why my interpreter is looking for a boolean would be appreciated!

Note. I am very new to F #

====

Fixed with improvements Courtesy of Foggy, Michael and Fedor

 type Cell = { data : int; next : (Cell option) ref} let rec insert compare (item: int) (list: (Cell option) ref) : unit = let c = {data = item; next = ref None} match !list with | None -> list := Some c | Some {data = d; next = remaining} -> if (compare(d, item)) then c.next := !remaining remaining := Some c else insert compare item remaining 
+5
source share
1 answer

You return a bool from your None match:

 | None -> list = cellToRList c 

An equal sign is a comparison operator. Thus, the compiler returns a function to return bool , but I assume that you intend to return unit .

In any case, whenever you do not understand the inferred types of your functions, try to annotate them explicitly. In your case do it

 let rec insert comp (item: int) (list: RList) : unit = 

And you will see the problem described above.

You can remove the type annotation after compilation.

+4
source

Source: https://habr.com/ru/post/1244539/


All Articles