3
$\begingroup$

I want to change a numerical list of the (examplary) form {1,3/2,5} to {1,{1,2},5}.

First solution

{3, 5/2, 1 } /.  Rational[a_ , b_] -> {Floor[a /b], Ceiling[a/b ]}  
(*{3, {2, 3}, 1}*)

works fine. Second try

{3, 5/2, 1} /. (in_ /; (! IntegerQ[in]) :> {Floor[in], Ceiling[in]}  )
(*{{3, 2, 1}, {3, 3, 1}}*)

fails.

What's wrong with my second version? Thanks!

$\endgroup$
3
$\begingroup$

Replace with level specification 1 gives the expected result:

Replace[{3, 5/2, 1}, (in_ /; (! IntegerQ[in]) :> {Floor[in], Ceiling[in]}), 1]

{3, {2, 3}, 1}

With ReplaceAll the pattern in_ /; (! IntegerQ[in]) matches {3, 5/2, 1} and it is applied to it to give {Floor[{3, 5/2, 1}], Ceiling[{3, 5/2, 1}]}.

$\endgroup$
  • $\begingroup$ Thanks, I got it! $\endgroup$ – Ulrich Neumann Feb 2 at 13:18

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.