在 F# 中缩放序列

发布于 2024-12-11 13:40:30 字数 710 浏览 1 评论 0原文

我试图按序列的第一个元素缩放序列,因此第一个元素始终为 1,然后后续元素是原始序列的第一个元素与第 n 个元素的比率。

这是我的代码,

       open System
       open System.Collections

           let squish1 (x:Double seq) =
                let r =  (Seq.head x:Double)
                Seq.fold (fun (xi:Double) (r:Double) -> xi/r);;

我在这个小向量上进行测试:-

                squish1 [|5.0; 1.0; 1.0; 1.0; 1.0; 1.0|];;

我已经输入了所有内容,因为我收到此错误消息

normaliseSequence.fsx(9,1):错误 FS0030:值限制。值“it”已被推断为具有泛型类型 val it : (Double -> '_a -> Double) 当 '_a :>序列
要么明确“it”的参数,要么如果您不希望它是通用的,请添加类型注释。

但显然我误解了,因为即使输入了所有内容我也会收到错误消息。我缺少什么?

非常感谢所有的建议。谢谢

I am trying to scale a sequence by the first element of the sequence, so the first element will always be one, and then subsequent elements are a ratio of the first element to the nth element of the original sequence.

Here is my code,

       open System
       open System.Collections

           let squish1 (x:Double seq) =
                let r =  (Seq.head x:Double)
                Seq.fold (fun (xi:Double) (r:Double) -> xi/r);;

And I test on this little vector:-

                squish1 [|5.0; 1.0; 1.0; 1.0; 1.0; 1.0|];;

I have typed everything because I get this error message

normaliseSequence.fsx(9,1): error FS0030: Value restriction. The value 'it' has been >inferred to have generic type
val it : (Double -> '_a -> Double) when '_a :> seq
Either make the arguments to 'it' explicit or, if you do not intend for it to be generic, >add a type annotation.

But clearly I am misunderstanding because I get the error message even with everything typed. What am I missing?

Any and all advice gratefully received. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

桃扇骨 2024-12-18 13:40:30

fold 还需要两个参数:种子值和序列。这有效:

let squish1 (x:Double seq) =
    let r =  (Seq.head x:Double)
    Seq.fold (fun (xi:Double) (r:Double) -> xi/r) 0.0 x

但是,我猜你可能想要 map 而不是 fold

let squish1 (x:Double seq) =
    let r =  (Seq.head x:Double)
    Seq.map (fun (xi:Double) -> xi/r) x

顺便说一句,我可能会这样写:

let inline squish1 (x:seq<_>) =
  let r = Seq.head x
  Seq.map (fun n -> n / r) x

现在它适用于所有支持除法的类型。

fold expects two more parameters, the seed value and the sequence. This works:

let squish1 (x:Double seq) =
    let r =  (Seq.head x:Double)
    Seq.fold (fun (xi:Double) (r:Double) -> xi/r) 0.0 x

However, I'm guessing you probably want map instead of fold:

let squish1 (x:Double seq) =
    let r =  (Seq.head x:Double)
    Seq.map (fun (xi:Double) -> xi/r) x

Incidentally, I would probably write it this way:

let inline squish1 (x:seq<_>) =
  let r = Seq.head x
  Seq.map (fun n -> n / r) x

Now it works for all types that support division.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文