Search code examples
haskellfunctional-programmingnim-lang

Find the first non-consecutive number in functional way in nim-lang


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.


Solution

  • import zero_functional
    import std/options
    
    func first_non_consecutive(arr:seq[int]):Option[int] =
      let x = arr --> filter(idx > 0) -->
         map((diff:it-arr[idx-1],val:it)) -->
         filter(it.diff > 1) --> take(1) 
      if x.len>0:
        return some(x[0].val)
    

    unlike the recursive one it wont cause a stack overflow with large inputs