首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用函数式在nim-lang中找到第一个非连续数

用函数式在nim-lang中找到第一个非连续数
EN

Stack Overflow用户
提问于 2022-11-06 00:43:22
回答 1查看 47关注 0票数 1

我是尼姆的新手,我尝试了一些代码挑战

根据https://www.codewars.com/kata/58f8a3a27a5c28d92e000144/nim

我可以用以下方法解决这个问题:

代码语言:javascript
复制
import options

proc first_non_consecutive*(arr: seq[int]): Option[int] =
    for i, item in arr:
      if i > 0 and item - arr[i-1] > 1:
        return some(item)

但我在寻找一种实用的方法来解决这个问题

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-08 22:02:59

这是我的第一个堆叠溢出的答案,所以我有点不知道该说什么。但是对于功能性解决方案来说,这应该是很好的!

还请注意,任何函数调用(如len(arr) )都可以更改为arr.len,我认为func只是一个注释过程的模板,说明它没有副作用。

代码语言:javascript
复制
import options

func isPrev1Below(arr: seq[int], idx: int): Option[int] = 
    if idx > len(arr) - 1:# incase we reach the end of the array
        return none(int)

    if arr[idx] - arr[idx-1] != 1:# if the difference between this and the previous are not 1, it's not consecutive
        return some(arr[idx])

    return isPrev1Below(arr, idx + 1)# otherwise returns the result of the next item.

func firstNonConsecutive*(arr: seq[int]): Option[int] = 
    isPrev1Below(arr, 1)# start on second item because it will never be first


echo firstNonConsecutive @[1,2,3,4,5,6,7,8]# equivelant to echo(firstNonConsecutive(@[1,2...]))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74332529

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档