Still very new to F#, so bare with me...

Is it possible to do something like this in F#

1
2
3
case str of
    | []     -> []
    | (x:xs) -> [(x,xs)]

where str is a string?

This was the best I could come up with:

1
2
3
case str.Length with
    | 0     -> []
    | _ -> [(str.[0],str.Remove(0,1))]

which is obviously pretty ... well, not pretty.

Regards, Egil.

F# pattern matching is extensible, so you can definitely write your own active pattern to match strings like that. See:

[link:msdn.microsoft.com]

By on 6/2/2009 1:03 PM ()

Thanks for the input guys, I look in to active patterns later on if I need the same kinda pattern matching again.

By on 6/3/2009 12:30 AM ()

One of my favorite Active Patterns lets me use Regex expressions in a match statement.

See Stack Overflow post here.

By on 6/3/2009 6:30 AM ()

As far as I know, I don't think you can deconstruct a string in a pattern match. In F# strings aren't represented as lists. However, you could just create a list out of it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 

> let str = "hello";;

val str : string = "hello"

> match Seq.to_list str with

| [] -> []

| x::xs -> [(x,xs)];;

val it : (char * char list) list = [('h', ['e'; 'l'; 'l'; 'o'])]

If it was a limited set of patterns, you could probably come up with an active pattern to remove some of the ugliness.

By on 6/2/2009 12:27 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper