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.

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.

You could determine that a term holds a list of integers that fall within the range of characters you consider to be a string:

-- GordonWeakliem - 05 Apr 2004

The Python Cookbook discusses how simplay asking isinstance is "UnPythonic" and has a discussion on "duck typing", in that their solution just asks if you can concatenate a string to an unknown object. I'm not sure how to address this. You could literally ask if (string-append an-object "") works w/o throwing an exception, but would anyone do this?

(define (is-string? s)
    (with-handlers ((not-break-exn?
                   (lambda (exn) 
                     #f)))
    (let ((s2 (string-append s ""))) #t)))

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