Home > Software engineering >  Find the first non-consecutive number in functional way in nim-lang
Find the first non-consecutive number in functional way in nim-lang

Time:11-11

I'm new to nim and trying some code challenges

According to https://www.codewars.com/kata/58f8a3a27a5c28d92e000144/nim

I can solve this kata with:

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)

but I'm looking for a functional way of solving this problem

Thanks.

CodePudding user response:

This is my first stackoverflow answer so I'm a little unsure on what to say. But this should be fine for a functional solution!

also note any function calls like len(arr) can be changed to arr.len, and func is I think just a template that annotates the procedure to say it has no side effects.

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...]))
  • Related