【问题标题】:Outputing y element after every nth elements in the list在列表中的每 n 个元素之后输出 y 元素
【发布时间】:2020-03-12 04:02:47
【问题描述】:

如何编写一个 F# 递归函数,在列表 xs 中的每 n 个元素之后插入指定的 y 元素,并且即使应用于无限列表也可以工作。

例如: 一个是

输入

let something n y xs = ... 
    ...

输入

something 2 'O' ['a'; 'b'; 'c'; 'd'; 'e'; 'f'];;

输出

['a'; 'b'; 'O'; 'c'; 'd'; 'O'; 'e'; 'f'; 'O'] 

输入

something 3 'O' ['a'; 'b'; 'c'; 'd'; 'e'; 'f'];;

输出

['a'; 'b'; 'c'; 'O'; 'd'; 'e'; 'f'; 'O']

另一个是

输入

something 5 'A' [1..10]

输出

['1'; '2'; '3'; '4'; '5'; 'A'; '6'; '7'; '8'; '9'; '10'; 'A']

【问题讨论】:

  • 重复的stackoverflow.com/questions/58847230/… 与问题相同。
  • 现在不在我的电脑上,但这听起来不像是使用几种现有的收集方法很难。你有什么理由要写一个递归方法吗?

标签: list recursion f#


【解决方案1】:

如果你们不介意的话,我会拍一张

let all = [ 'a'; 'b'; 'c'; 'd'; 'e' ]

let rec insertEvery n value indexed =
    let loop = insertEvery n value
    match indexed with
    | [] -> []
    | (indx, hd) :: tl ->
        match indx with
        | i when n <> 0 && ((i + 1) % n) = 0 -> hd :: value :: loop tl
        | _ -> hd :: loop tl

all
|> List.indexed
|> insertEvery 3 'x'
|> printf "%A\n"
$ fsi insertEvery.fsx 
['a'; 'b'; 'c'; 'x'; 'd'; 'e']

刚刚进入 ocamlish 的一面 ...
...欢迎有建设性的批评者 :)

【讨论】:

    猜你喜欢
    • 2012-09-21
    • 2015-09-11
    • 2020-03-11
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2014-10-29
    相关资源
    最近更新 更多