小编Dev*_*ewb的帖子

元组的GetHashCode黑客攻击

知道为了获得两个对象的哈希码,通常的做法是对它们各自的哈希码进行XOR,我想检查一下Tuple如何处理其中的情况Item1 == Item2.这是我在源代码中找到的:

internal static int CombineHashCodes(int h1, int h2) {
        return (((h1 << 5) + h1) ^ h2);
    }
Run Code Online (Sandbox Code Playgroud)

我假设这是为了避免为所有相等的对象使用相同的哈希码,因为x ^ x = 0.为什么h1 << 5呢?这有什么特别的原因5吗?可能只是1?请帮我理解.

.net c# hashcode

4
推荐指数
1
解决办法
1237
查看次数

为什么F#编译器不能在这种情况下推断类型?

似乎printPerson函数中的p参数不能被推断为Person,但是intelisense显示我正在传递的两个printPerson调用p:Person.请帮我理解我做错了什么?

type Person (name:string) = 
        member e.Name = name

type EmployeeNode = 
    | Leader of Person * int * list<EmployeeNode>
    | Employee of Person * int

let printPerson level p = 
    printfn "%s %s" <| String.replicate (level) "#" <| p.Name 

let rec print node  = 
    match node with
    | Employee(p, level) -> printPerson level p
    | Leader(p, level, nodes) -> 
        printPerson level p
        List.iter print nodes
Run Code Online (Sandbox Code Playgroud)

f# type-inference

4
推荐指数
3
解决办法
131
查看次数

将 NUnit 与通用可区分联合结合使用

我正在尝试使用 FsUnit(在幕后它使用 NUnit)来测试我的 F# 代码,但它在处理通用可区分联合时遇到问题。我理解为什么会发生这种情况,但我正在尝试找到一种在不注释我的预期值的情况下编写测试的方法。有什么建议吗?是否有更适合于此的框架?

type OptionWithReason<'a> =
  | Some of 'a
  | None of string

let reason = "division by 0 is not yet supported"
let safeDivide x y = 
    if y = 0 then 
        None reason
    else
        Some(x/y)

let result = safeDivide 1 0

let expected = None reason
let expectedExplicit: int OptionWithReason = None reason

let test1 = result = expected //true
let test2 = result = expectedExplicit //true

NUnit.Framework.Assert.AreEqual(expectedExplicit,result) //pass
NUnit.Framework.Assert.AreEqual(expected,result) //fail :(
Run Code Online (Sandbox Code Playgroud)

generics f# nunit discriminated-union

2
推荐指数
1
解决办法
167
查看次数

标签 统计

f# ×2

.net ×1

c# ×1

discriminated-union ×1

generics ×1

hashcode ×1

nunit ×1

type-inference ×1