I want to call a function that would perform a function rather than assigning an expression to them.



n=1; wordSplit = {};
stringWord = string; 
While[n-1 != StringLength[stringWord], wordSplit = Append[wordSplit, StringTake[stringWord, {n,n}]] n++];

How can I call this 'functionA' with a string input rather than directly modifying the variable in its cell?

  • 1
    $\begingroup$ take a look at := and Block, use function[input_String]:=Block[{},code] and than call it via function["test string"] $\endgroup$ – gogoolplex Oct 21 '14 at 10:32
  • $\begingroup$ Awesome Block is what I was looking for. $\endgroup$ – Tadashi Kikuno Oct 21 '14 at 11:06

Alhough your function may be an example and you could use Block or Module to build your list using looping and Append, list manipulation offers great advantages.

For the example of splitting a string (including WhiteSpaceCharacter) the following are ways to do it (starting with the built-in function Characters).

Characters["this is"]

(*mapping StringTake to list of positions, i.e. take 1st, 2nd,... etc*)

fun[str_] := StringTake[str, {#}] & /@ Range[StringLength@str]

(* using Table*)

tab[str_] := Table[StringTake[str, {j}], {j, StringLength@str}]

(*extracting characters*)

StringCases["this is", 
 x : (LetterCharacter | WhitespaceCharacter) -> x]

I post this just as motivation to explore the documentation and this site which as excellent resources, e.g. searchng for alternatives to loops in Mathematica.

  • $\begingroup$ Thank you, that is super neat. I completely agree with you. I read somewhere that looping is not always a solution and most of the time more slower than using already built-in functions. I will explore the documentation more. $\endgroup$ – Tadashi Kikuno Oct 21 '14 at 11:18

Maybe using Module, something like this:

functionA[string_] := Module[{stringWord, n, wordSplit},
  n = 1;
  wordSplit = {};
  stringWord = string;
  While[n - 1 != StringLength[stringWord], 
  wordSplit = 
    Append[wordSplit, StringTake[stringWord, {n, n}]] n++];

Another option might be to use Block.

  • $\begingroup$ Great! Module and Block both worked. $\endgroup$ – Tadashi Kikuno Oct 21 '14 at 11:07
  • 3
    $\begingroup$ @TadashiKikuno You should use Module for localization unless you know you need Block. (see here). These are used for localization. If there are no variables to localize, just use CompoundExpression, i.e. f[] := (command1; command2; ...) $\endgroup$ – Szabolcs Oct 21 '14 at 14:29

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.