Frederik
Frederik

Reputation: 667

F# record and evaluating of this

I'm struggling a bit with a F#-assignment, which I hope you can answer for mere: I have that

We will use the type OrderedList<’a> declared as follows

type OrderedList<’a when ’a : equality> = 
    { front: ’a list
    ; rear: ’a list}

For instance, the value let ex = {front = [’x’]; rear = [’z’;’y’]} has type OrderedList<char> and represents the ordered list [’x’, ’y’, ’z’].

The question that I'm struggling with is:

We define the canonical representation of an ordered list to be the representation where the rear list is empty. Declare a function canonical:OrderedList<’a>->OrderedList<’a>, where canonical ol returns the canonical representation of ol.

Just as a startup, I've tried something:

let canonicial (list:OrderedList<'a>)= 
    match list with
    | {x::xs}, {y::xss} -> if x = y then "SUCCESS!!!!" else failwith "FEJL!!!"
    | _ -> failwith "Some"

My issue is that I don't know how to get to the element in the type / the syntax for this. I know the function has not been solved correctly, but right now I focus mostly on the syntax.

Hope to get some help!

Upvotes: 0

Views: 90

Answers (3)

Sehnsucht
Sehnsucht

Reputation: 5049

Another way to do it granted that @ already takes care of returning the "other list" if one is empty (so shouldn't be an overhead to always append) :

let canonical ol = { ol with front = ol.front @ List.rev ol.rear; rear = [] }
// or
let canonical { front = fs; rear = rs } = { front = fs @ List.rev rs; rear = [] }

Upvotes: 1

Frederik
Frederik

Reputation: 667

Thanks, thanks, thanks! Now I better understand this topic! I rewritten your code to:

let canonical2 (ol:OrderedList<'a>) : OrderedList<'a> = 
    match ol with
    |{ front = _; rear = []} -> ol
    |{ front = f; rear = r} -> {front = f @ List.rev r; rear = []}

Upvotes: 1

Random Dev
Random Dev

Reputation: 52280

Well I think I can give you the solution now (you surely have more problems to solve):

let canonical = 
   function   
   | { front = _; rear = [] } as ol -> ol
   | { front = fs; rear = rs } -> { front = fs @ List.rev rs; rear = [] }

as you can see the first case is when the rear is already empty - here it's enough to give to original back

in the other case we have to get a new OrderedList<'a> with the reversed old rear appended to the old front - that's it - you don't even need the constraint on 'a - and indeed I find it strange to put it there - usually it's better to but the constraints on the functions in FP - but well different styles and stuff.

I hope this helps you out a bit

BTW: I used function on purpose - you should try to convert this into your usual match ... with ... style so you can get your syntax right

Upvotes: 2

Related Questions