Write an F# function cut xs that cuts a list into two equal parts: Assume that t
ID: 2247207 • Letter: W
Question
Write an F# function cut xs that cuts a list into two equal parts:
Assume that the list has even length.
To implement cut, first define an auxiliary function gencut(n, xs) that cuts xs into two pieces, where n gives the size of the first piece:
Paradoxically, although gencut is more general than cut, it is easier to write! (This is an example of Polya's Inventor's Paradox: "The more ambitious plan may have more chances of success.")
Another Hint: To write gencut efficiently, it is quite convenient to use F#'s local let expression
Explanation / Answer
let cut xs = gencutdata((List.length xs) / 2, xs)
let rec gencutdata(n, listdata) =
let rec cut n (listvalue : int list) (listdata : int list) =
match (n , listdata ) with
| 0, _ -> listvalue, listdata
| _, [] -> listvalue, listdata
| _, b :: listdata -> cut (n - 1) (List.rev (b :: listvalue )) listdata
cut n [] listdata
In the above program gencutdata function will be called recursivly and that cuts xs into two pieces.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.