I have a recursive function that does some work to an object for a repeatedamount of times.

f[h_, repeated_Integer /; repeated >= 0, level_Integer /; level > 0] :=
  (* Do some stuff to h using level then call foo on h *)
  foo[h, If[level < repeated, f[h, repeated, level + 1], final[h] ]]

I mostly pass in 1 for the level parameter but there are times where I want to start at a different level (aka depth) of h. I found I could use the longhand Optional to skip passing in 1 for level all the time.

Optional[level_Integer /; level > 0 , 1]

However, before this I tried using shorthand optional : with no success.

(level_Integer : 1) /; level > 0


(level_Integer /; level > 0) : 1

Both of these give syntax errors. Is there a way to do this with shorthand optional :?

  • 1
    $\begingroup$ I though it should have duplicate but I only found this related question about PatternTest+Optional. 4937 $\endgroup$ – Kuba Apr 9 '15 at 10:14
  • $\begingroup$ @Kuba I see. I didn't realise you could condition between the function signature and the SetDelayed. Thanks. I think I'll leave this one with longhand if this is the only option. I think it is cleaner. However I now can add some parameter interaction test with this new found technique. Like g[x_Integer /; x >= 0, y_Integer /; y > 0] /; y > x := {x , y}. Now that is powerful stuff. :-) $\endgroup$ – Edmund Apr 9 '15 at 10:17

I think you can move condition outside brackets:

f[x_Integer : 1] /; x >= 0 := {x}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.