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$
0

1 Answer 1

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$
1
  • $\begingroup$ Thanks, I got it! $\endgroup$ Feb 2, 2019 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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