s c h e m a t i c s : c o o k b o o k

/ StringRecipes / Cookbook.IsAString

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Testing Whether an Object is a String

Problem

You need to test if an object is a string.

Solution

The string? predicate is what you want:
> (string? "foo")
#t
> (string? #\f)
#f
> (string? (list #\f #\o #\o))
#f
Notice that a character is not a string. Also, even though we've said that a string is a list of characters, a list of characters is not 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)))

-- GordonWeakliem - 05 Apr 2004

Scheme definitely doesn't have built-in duck typing, by design, but of course you can implement it, using e.g. generic functions. I suspect the Python idea of not asking isintance also comes in part from general OO principles, where most things should be done with polymorphic method calls, and you shouldn't have to ask what type something is, most of the time.

None of this applies to standard Scheme. However, with an object system, like PLT's classes or Swindle's CLOS implementation, then things like this are possible. For example, with Swindle, you could define string-append as a generic function that worked on all the basic Scheme types, which would give you duck typing in that case. I'm not sure offhand whether Swindle has anything like this built-in.

-- AntonVanStraaten - 07 Apr 2004

CookbookForm
TopicType: Recipe
ParentTopic: StringRecipes
Other Parents:
Next Topic: StringSubstring

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, 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