DEV Community

Discussion on: Can you spot the problem in the implementation of nthElement?

Collapse
 
leojpod profile image
leojpod

you could perhaps optimize it to leverage the "tail-recurssive" optimization by doing something like this btw:

nthElementHelper : List a -> Int -> Result String a
nthElementHelper list n =
  case (n, list) of
    (_, []) ->
      Err ("List too short by " ++ String.fromInt (n+1) ++ pluralize n "element" "elements")

    (0, x :: _) ->
      Ok x
    (nth, _ :: rest) ->
      nthElementHelper rest (nth-1)
Collapse
 
leojpod profile image
leojpod

although come to think of it you're already doing "tail-recurssion"

Collapse
 
dwayne profile image
Dwayne Crooks

yeah, I'm already doing that

Thread Thread
 
leojpod profile image
leojpod

I still prefer the case of on a tuple than a case of with some if then else branching inside but that's personal taste :)