【问题标题】:F#: Reducing an array of numbers as strings to a single integerF#:将数字数组作为字符串减少为单个整数
【发布时间】:2015-09-06 17:51:56
【问题描述】:

我有一个字符串数组,称之为a,其中每个单独的字符串代表一个数字。我还有一个函数f : int -> int -> int,我想用它来“将a 减少到一个数字”。我想写:

a |> Array.reduce (fun x y -> f (int32 x) (int32 y))

但这不起作用,因为“减少”的类型禁止我从f 返回整数(因为a 是一个字符串数组

是否有一种 功能性 方法可以使这项工作而无需返回 来自f 的字符串或预先将字符串数组转换为 int 数组?

【问题讨论】:

    标签: f#


    【解决方案1】:

    首先使用Array.reduce 映射

    如果您不想调整 f 来处理字符串,并且您想使用 Array.reduce 那么是的,我想您应该先转换(老实说:这似乎比手动使用您的wrapper-lambda) - 那么为什么不直接使用

    a
    |> Array.map int32
    |> Array.reduce f
    

    改为?

    如果您担心生成中间数组的开销,您可以随时将Array.Seq. 懒惰地切换到它:

    a |> Seq.map int32 |> Seq.reduce f
    

    使用Array.fold

    除此之外,您还可以随时fold 满足您的心愿:

    a |> Array.fold (fun n s -> n + int32 s) 0
    

    所以你可以把它称为更多功能或不;)

    【讨论】:

    • 是的,我不想先转换整个数组。我不知道“折叠”方法可以做到这一点。感谢您指出这一点。
    • fold 可以做一切(它是列表的基本操作,因为它会影响列表定义)
    • @Carsten 您能否详细说明“因为它会影响列表定义”是什么意思?
    • @sebhofer 它是 list's catamorphism,在 lambda-calculus 中通常是 introduce lists with their fold - 但这只是 smart-talk 的简单观察,即折叠 fold f i ls (好吧实际上是List.foldBack)保持列表结构ls = 1::2::3::[]不变,只是用i替换[],用::替换f(作为bin.运算符):fold (+) 0 ls = 1+(2+(3+0))
    • 谢谢卡斯滕!我需要稍微消化一下(我是函数式编程的新手)...
    猜你喜欢
    • 2020-01-03
    • 2022-11-13
    • 2012-06-18
    • 2014-11-15
    • 2014-04-13
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    相关资源
    最近更新 更多