Я пытаюсь написать метод в F #, который возвращает новый экземпляр родового типа, основанный на типе значения, переданного в метод. В FSI:Ошибка несоответствия типа. Ошибка ввода типа F #?
open System.Collections.Generic
type AttributeIndex<'a>() =
inherit SortedDictionary<'a, HashSet<int array>>()
let getNewIndexForValue (value: obj) : AttributeIndex<_> =
match value with
| :? string -> new AttributeIndex<string>()
| :? int -> new AttributeIndex<int>()
| :? float -> new AttributeIndex<float>()
| :? bool -> new AttributeIndex<bool>()
| _ -> failwith "bad value type"
let someIndexes = [
getNewIndexForValue 9;
getNewIndexForValue "testString";
getNewIndexForValue false;
getNewIndexForValue 5.67;
]
someIndexes;;
Это не компилируется с ошибкой
error FS0001: Type mismatch. Expecting a AttributeIndex<string>
but given a AttributeIndex<int>
The type 'string' does not match the type 'int'
Я не могу показаться, чтобы выяснить, как получить экземпляр атрибута с типом парами на основе типа значение параметра передается в функцию. Я пробовал пару других вариантов, но все они приводят к ошибке несоответствия такого же типа. Любая помощь будет принята с благодарностью. Благодаря!!
UPDATE:
Спасибо за ответы. Я получаю это сейчас. Итак, теперь я пытаюсь вернуть свой getNewIndexForValue не общий шаблон класса AttributeIndex. Я реализовал это в C# и компилирует и работает, как я ожидал:
using System;
using System.Collections.Generic;
namespace Example {
public class AttributeIndexBase : SortedDictionary<object, HashSet<int[]>> { }
public class AttributeIndex<T> : AttributeIndexBase {
public void AddToIndex(T indexValue, int[] recordKey) {
if (!this.ContainsKey(indexValue)) {
this.Add(indexValue, new HashSet<int[]> { recordKey });
}
else {
this[indexValue].Add(recordKey);
}
}
}
class Program {
static int Main(string[] args) {
var intIdx = GetIndexForValue(32);
var boolIdx = GetIndexForValue(true);
var doubleIdx = GetIndexForValue(45.67);
var someIndexes = new List<AttributeIndexBase> {
intIdx,
boolIdx,
doubleIdx
};
return 0;
}
static AttributeIndexBase GetIndexForValue(object value) {
switch (value.GetType().Name.ToLower()) {
case "int32" :
return new AttributeIndex<int>();
case "single" :
return new AttributeIndex<float>();
case "double" :
return new AttributeIndex<double>();
case "boolean" :
return new AttributeIndex<bool>();
default :
throw new ArgumentException("The type of the value param is not allowed", "value");
}
}
}
}
Однако, пытаясь порт это F # не работает:
module example
open System
open System.Collections.Generic
type AttributeIndexBase() =
inherit SortedDictionary<obj, HashSet<int array>>()
type AttributeIndex<'a>() =
inherit AttributeIndexBase()
let getNewIndexForValueType (value: ValueType) : AttributeIndexBase =
match value with
| :? int -> new AttributeIndex<int>()
| :? float -> new AttributeIndex<float>()
| :? bool -> new AttributeIndex<bool>()
| _ -> failwith "bad value type"
let someIndexes = [
getNewIndexForValueType 9;
getNewIndexForValueType false;
getNewIndexForValueType 5.67;
]
Это, мне кажется, будет довольно прямой порт (за исключением F # версии я сдерживая его просто ValueType), но я получаю ошибку:
error FS0001: This expression was expected to have type AttributeIndexBase
but here has type AttributeIndex<int>
ли F # на самом деле просто не поддерживает бросок от дочернего к родительскому типу, например, C#?
Что вы собираетесь делать с «someIndexes» позже? – Brian
Чтобы ответить на ваш последний вопрос, прочитайте «Типы объектов кавычек/Upcasting» в MSDN: http://msdn.microsoft.com/en-us/library/dd233220.aspx – Jason