开发者

Comparisons of items in a list

开发者 https://www.devze.com 2023-02-03 23:35 出处:网络
I have written this method which given a number and a list will return a new list with the number inserted into the list at the correct position based on its value. (I\'m doing an Insertion sort.)

I have written this method which given a number and a list will return a new list with the number inserted into the list at the correct position based on its value. (I'm doing an Insertion sort.)

let rec insertinto number numbers =
  match numbers with
  | [] -> [number]
  | head::tail -> if head > number then number::numbers else head::(insertinto number tail)

F# guesses the type of this method to be :

val insertinto : 'a -> 'a list -> 'a list开发者_如何学编程 when 'a : comparison

If I test this method with

[4; 10; 15] |> insertinto 12

I get

val it : int list = [4; 12; 10; 15]

Which is clearly wrong. The comparison 'head > number' is not working correctly.

To get it to work I have to specify the type of the numbers parameter :

let rec insertinto number numbers: int list =

Then it all works, but I dont want to use an int list all the time, I want this to work with any type of list. As long as the type implements comparison it should work, surely.

Why would this work with an int list and not a generic list? What am I missing?

edit

ok, this appears to be a Mono only problem.


I just tested the code on Mac using Mono (version 2.8) and MonoDevelop with the latest F# integration and the first function (without type annotations) works as expected.

However, I wouldn't be too surprised if this was a bug in earlier version of Mono. There were all sorts of issues in 2.6.x. Giving incorrect result is weird error (more common was some error message or crash), but it may be caused by some issue. Can you check your version of Mono?

I'm using this and it works fine:

fsmac:~ tomaspetricek$ mono -V
Mono JIT compiler version 2.8 (tarball Thu Oct  7 12:23:27 MDT 2010)
Copyright (C) 2002-2010 Novell, Inc and Contributors. www.mono-project.com

Although you can run F# on Mono 2.6.x, it is highly recommended to use 2.8 (which fixes many issues with generics that were blocking for F#)

0

精彩评论

暂无评论...
验证码 换一张
取 消