gpt4 book ai didi

f# - 我们可以使用更通用的类型来缩短 F# 中的这段代码吗?

转载 作者:行者123 更新时间:2023-12-05 01:23:29 26 4
gpt4 key购买 nike

我在阅读“Programming F# 3.0”时遇到了这段代码:

type BitCounter =

static member CountBits (x : int16) =
let mutable x' = x
let mutable numBits = 0
for i = 0 to 15 do
numBits <- numBits + int (x' &&& 1s)
x' <- x' >>> 1
numBits

static member CountBits (x : int) =
let mutable x' = x
let mutable numBits = 0
for i = 0 to 31 do
numBits <- numBits + int (x' &&& 1)
x' <- x' >>> 1
numBits

static member CountBits (x : int64) =
let mutable x' = x
let mutable numBits = 0
for i = 0 to 63 do
numBits <- numBits + int (x' &&& 1L)
x' <- x' >>> 1
numBits

我试图通过制作一个辅助功能来缩短这部分:

type BitCounter =

static member CountBitsWithRangedMask x upBound typeConverter =
seq { for i = 0 to upBound do yield 1 <<< i }
|> Seq.map typeConverter
|> Seq.map ((&&&) x)
|> Seq.filter ((<>) (typeConverter 0))
|> Seq.length

static member CountBits (x : int16) =
BitCounter.CountBitsWithRangedMask x 15 int16

static member CountBits (x : int) =
BitCounter.CountBitsWithRangedMask x 31 int

static member CountBits (x : int64) =
BitCounter.CountBitsWithRangedMask x 63 int64

但是static member CountBits (x : int)导致编译错误:

error FS0001: This expression was expected to have type
int16
but here has type
int

所以我想知道是否可以在 Haskell 中对 CountBitsWithRangedMask 的第一个参数添加一些约束,例如 Integral a。或者有没有其他方案可以简化原来的代码?

最佳答案

您可以使用 LanguagPrimitives.GenericOneLanguagPrimitives.GenericZero 结合 inline 来实现这一点。

let inline CountBitsWithRangedMask x upBound =
seq { for i = LanguagePrimitives.GenericZero to upBound do yield LanguagePrimitives.GenericOne <<< i }
|> Seq.map ((&&&) x)
|> Seq.filter ((<>) (LanguagePrimitives.GenericZero))
|> Seq.length

let test16 (x:System.Int16) = CountBitsWithRangedMask x 15
let test32 (x:System.Int32) = CountBitsWithRangedMask x 31
let test64 (x:System.Int64) = CountBitsWithRangedMask x 63

使用它我们也不需要 typeConverter 参数,因为编译器会自动完成所有事情。

对于此类问题,这是一种相当通用的方法。

关于f# - 我们可以使用更通用的类型来缩短 F# 中的这段代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16162722/

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