MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Function returns null

  • To: mathgroup at
  • Subject: [mg104724] Re: Function returns null
  • From: Bill Rowe <readnews at>
  • Date: Sun, 8 Nov 2009 06:42:37 -0500 (EST)

On 11/7/09 at 6:46 AM, mgreene at (Michael Greene) wrote:

>I'm getting an unexpected result when I remove a print statement
>from my function. The function computes a single digit sum of digits
>and returns what I expect as long as the print statement just prior
>to the function exit is present. I can verify that by invoking the
>function within a print statement, e.g.,

>Print["sOd returned - ",sOd[3329]]

>When I remove the print  within the function, the function returns a
>null result. What simple point am I missing ? Does the := operator
>have something to do with this?

>Here is the function: (with embedded print statement)

>sOd[x0_] := Module[{sodv, x, digit},
>x = IntegerPart[x0]; (* ensure we have an integer input*)
>sodv = x;
>If[(x > 9), {              (* sum digits if input has two or more digits*)
>sodv = 0;
>While[x > 0,
>digit = (FractionalPart[x /10])*10;
>sodv = sodv + digit;
>x = IntegerPart[x/10];
>sodv = sOd[sodv];  (* check for multiple digit sum  *)
>Print["sOd returns -", sodv];  (* remove this and function returns null*)
>Return[sodv];             (* return single digit sum *)

Module returns the result of the last expression which is
Return[sodv];. This is a compound expression equivalent to
Return[sodv];Null which is why you get the Null. Change this to
Return[sodv] and things will behave as you expected.

Also, I note the code is much more complex than need by to
compute the sum of digits in an integer. The following code has
the same functionality as your code:

sOd[x_Integer] := FixedPoint[Total[IntegerDigits@#] &, x]

  • Prev by Date: Re: Mathematica skill level snippet(s)
  • Next by Date: Re: What is going on!?!
  • Previous by thread: Re: Function returns null
  • Next by thread: Re: Function returns null