e r l a n g : c o o k b o o k

/ Erlang.StringIsItTest

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Testing Whether an Object is a String

Problem

You need to test if an object is a string. Since Erlang does not have objects per se, the goal here is really that you want to test if a term is a string.

Solution

You can't! An Erlang string is just a list of characters (really, a list of integer values). So, the variable you are examining could be a list of letters, a set of coordinates, or a set of bytecode for Donald Knuth's MMIX machine.

About the best you can do is determine that the term you are evaluating is a list or not. For that, use the Erlang built-in-function is_list:

1> A="This is fun!".
"This is fun!"
2> is_list(A).
true
3> B=12.
12
4> is_list(B).
false

If you were very concerned that a term was printable, you could verify that it consists of a list of integers that fall within the range of characters you consider to be a string:

1> Fun = fun(XX) ->         
1>     if XX < 0 -> false;  
1>        XX > 255 -> false;
1>        true -> true      
1>     end                  
1> end.
#Fun<erl_eval.6.39074546>
2> Is_String = fun(XY) ->            
2>     case is_list(XY) of           
2>         false -> false;           
2>         true -> lists:all(Fun, XY)
2>     end                           
2> end.
#Fun<erl_eval.6.39074546>
3> A.
"This is fun!"
4> Is_String(A).
true
5> C. 
[2000,1982,199891]
6> Is_String(C).
false

-- BrentAFulgham - 20 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: StringRecipes
TopicOrder: 020

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest