(yes, this is a stale post - but since I had the same problem, figure I'll add an explanation to DeeJay's code to help out the next guy...)

The heart of the matter is that F#'s containers are all done in a "functional" style. Basically, this means they are immutable. Instead of manipulating elements held in a single mutable map object, the Map.add function returns a new map comprised of the given map and the supplied new key/element pair.

While it would be easy enough to substitute System.Collections.Generic.Dictionary into your code, let's take a look at how to use the Map in a functional setting.

The inner loop in DeeJay's code above (modified slightly, below) uses "List.fold_left" to accumulate a map with the keys found from a supplied list and an associated boolean value. The fold_left function accumulates intermediate maps as it folds the list (starting at the left), then returns the final accumulated resulting Map. Since the inner nodes in each intermediate map are shared between each of these maps, the operation is fairly efficient in both time and space.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#light
type dayofweek = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday
 
let is_weekend_map =

	let isWeekend day = match day with
											| Saturday | Sunday -> true
											| _                 -> false

	[Monday;Tuesday;Wednesday;Thursday;Friday;Saturday;Sunday]
	|> List.fold_left
				 (fun acc key ->
						 acc
						 |> Map.add key (isWeekend key) )
				 Map.empty
By on 10/14/2007 11:25 PM ()

Use my all time favourite function... fold... in this case, left fold

1
2
3
4
5
6
7
8
9
10
11
12
type dayofweek = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday


type daycategory = Weekday | Weekend


let is_weekend =
  let f day = if (day = Saturday) || (day = Sunday) then Weekday else Weekend in
    List.fold_left 
      (fun map day -> Map.add day (f day) map)
      Map.empty
      [Monday;Tuesday;Wednesday;Thursday;Friday;Saturday;Sunday]

As comparison is auto implemented for dayofweek... the custom comparison code is not need... at least for this section... and because of that you don't need to 'make' the map with a custom comparator... the standard map functions will use the built in *compare* (Pervasives).

see previous article: [link:cs.hubfs.net]

By on 7/5/2006 8:56 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