gpt4 book ai didi

algorithm - F# 算法中的意外 NullReferenceException

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:31:04 24 4
gpt4 key购买 nike

我正在尝试使用 F# 重写 Richard Bird 的 Pearls of Functional Algorithm Design 中的一些 Haskell 算法,但遇到了我不理解的 NullReferenceException。

Haskell 算法:

unmerges       :: [a] -> [([a], [a])]
unmerges [x,y] = [([x], [y]), ([y], [x])]
unmerges (x:xs) = [([x], xs), (xs, [x])] ++
concatMap (add x) (unmerges xs)
where add x (ys, zs) = [(x:ys, zs), (ys, x:zs)]

...按预期工作:

*Main> unmerges [1,2]
[([1],[2]),([2],[1])]
*Main> unmerges [1,2,3]
[([1],[2,3]),([2,3],[1]),([1,2],[3]),([2],[1,3]),([1,3],[2]),([3],[1,2])]

我的 F# 版本:

let concatMap f m = List.map (fun x -> f x) m |> List.concat

let rec unmerges (ints: 'a list) : ('a list * 'a list) list =
match ints with
| [] -> []
| [x; y] -> [([x], [y]); ([y], [x])]
| x :: xs -> [([x], xs); (xs, [x])] @
(let add x (ys, zs) = [(x::ys, zs); (ys, x::zs)] in
concatMap (add x) (unmerges xs))

... 匹配两个元素列表时效果很好,但在匹配较长列表模式时会抛出错误:

> unmerges [1;2];;

val it : (int list * int list) list = [([1], [2]); ([2], [1])]

> unmerges [1;2;3];;

System.NullReferenceException: Object reference not set to an instance of an object
at Microsoft.FSharp.Core.Operators.op_Append[Tuple`2] (Microsoft.FSharp.Collections.FSharpList`1 list1, Microsoft.FSharp.Collections.FSharpList`1 list2) [0x00000] in <filename unknown>:0
at Microsoft.FSharp.Primitives.Basics.List.concat[Tuple`2] (IEnumerable`1 l) [0x00000] in <filename unknown>:0
at Microsoft.FSharp.Collections.ListModule.Concat[Tuple`2] (IEnumerable`1 lists) [0x00000] in <filename unknown>:0
at FSI_0055.concatMap[Tuple`2,Tuple`2] (Microsoft.FSharp.Core.FSharpFunc`2 f, Microsoft.FSharp.Collections.FSharpList`1 m) [0x00000] in <filename unknown>:0
at FSI_0055.unmerges[Int32] (Microsoft.FSharp.Collections.FSharpList`1 ints) [0x00000] in <filename unknown>:0
at <StartupCode$FSI_0057>.$FSI_0057.main@ () [0x00000] in <filename unknown>:0
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0
Stopped due to error

我尝试单独定义 add,但没有突出显示任何问题。如果您对异常有任何见解和/或有关如何调试的建议,我将不胜感激。

最佳答案

郑重声明——这确实是一个 Xamarin 错误(细节尚不清楚,但在当前的 alpha 版本 5.10 和 Mono 4.2.1 中已解决)。 – THK Sep 22 at 2:23

关于algorithm - F# 算法中的意外 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32621571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com