[Haskell-cafe] Re: How to get subset of a list?

oleg at pobox.com oleg at pobox.com
Thu Nov 30 23:02:21 EST 2006

Huazhi (Hank) Gong wrote:

> Like given a string list s="This is the string I want to test", I want to get
> the substring. In ruby or other language, it's simple like s[2..10], but how
> to do it in Haskell?

Quite simply, actually:

> infixl 1 %%
> str %% idxs = map (str !!) idxs

That is it. Not the most efficient, but gets the job done.

> tstring = "This is the string I want to test"
> test1 = tstring %% [2..10]

	*Sub> test1
	"is is the"

> However, like I want to choose s[1,3,6,10] or something like this.
> Are there some straightforward function or operator for doing this
> job?

Yes, see above.

> test2 = tstring %% [1,3,6,10]

	*Sub> test2

Indices don't have to be in the increasing order

> test3 = tstring %% [10,6,3,1]

	*Sub> test3

or in any order...

> test4 = tstring %% [10,6,3,1]++[2..10]

	*Sub> test4
	"esshis is the"

Of course if one cares about the overhead of running code (rather than
the overhead of writing code), one would probably ask, as several
posters did, if the list of characters is the right data structure and
if the problem indeed calls for random access to the elements of the

More information about the Haskell-Cafe mailing list