PDA

View Full Version : standard ML functional programming "Efficient Code"


edeita2
04-13-2004, 09:56 PM
The below codes I wrote in ML are working 100 %, but I wonder if there is a more efficient & elegant way of writing them in ML.
Problem description: write a pattern which will bind the specified value to the identifier x.

val c = {Alpha="Joe",Beta=35,Gamma="Dog",Delta=false};"Dog"

My solution:

- val c = {Alpha="Joe",Beta=35,Gamma="Dog",Delta=false};
val c = {Alpha="Joe",Beta=35,Delta=false,Gamma="Dog"}
: {Alpha:string, Beta:int, Delta:bool, Gamma:string}
- val {Alpha = z, Beta = y, Gamma = x, Delta = w} = c;
val z = "Joe" : string
val y = 35 : int
val w = false : bool
val x = "Dog" : string
- val {Gamma = x, ...} = c;
val x = "Dog" : string


val d = [9, 2, 7, 12, 14, ~1];2

My solution:

- val d = [9,2,7,12,14,~1];
val d = [9,2,7,12,14,~1] : int list
- val [_, x, _, _, _, _] = d;
stdIn:17.1-17.27 Warning: binding not exhaustive
_ :: x :: _ :: _ :: <pat> :: <pat> = ...
val x = 2 : int

GnuVince
04-14-2004, 12:12 PM
For your second:

val x = List.nth(d, 1);


Not sure about the first one.

edeita2
04-15-2004, 12:40 PM
Originally posted by GnuVince
For your second:

val x = List.nth(d, 1);


Not sure about the first one.

thanks for the idea...but it`s not a pattern. I think I`m gonna stick to those ones, cuz` I couldn`t find any alternative solution as far as "pattern technique" goes...

jemfinch
04-18-2004, 09:07 PM
You shouldn't use pattern matching to match anything but the head/tail of lists. GnuVince's method is better than yours.

Jeremy