简体   繁体   中英

Translate merge function from Haskell to F#

I have this function in haskell which I would like to code in F# using native syntax and not the array functions such as map2.

Haskell :

merge [] ys = ys
merge (x:xs) ys = x:merge ys xs

This code merges two lists index-wise like this:

INPUT:  [1,2,3,4,5] [11,12,13,14]
OUTPUT: [1,11,2,12,3,13,4,14,5]

I tried doing it in F# and got this but it of course doesn't compile:

let rec mux x y = function
| [] -> []
| x::xs y::ys -> x::y::mux(xs,ys)

I am really struggling to work with two arrays in the pattern matching, thanks for any help you can give.

The Haskell function doesn't actually match on the two parameters. It only matches on the first parameter and takes the second parameter as is.

In F#, you can match on the first argument, and return a function that processes the second argument:

let rec mux = function
  | [] -> (function ys -> ys)
  | x::xt -> (function ys -> x :: mux ys xt)

But I find it clearer (and I think it's more efficient — at least it is in OCaml) to take in all the arguments at once, then analyze the argument you need to discriminate on:

let rec mux xs ys =
  match xs with
  | [] -> ys
  | x::xt -> x :: mux ys xt

If you wanted to match on both variables, there would be several solutions. You could nest function constructs:

let rec mux = function
  | [] -> (function [] -> … | y::yt -> …)
  | x::xt -> (function [] -> … | y::yt -> …)

But here again I prefer nesting match constructs:

let rec mux xs ys =
  match xs with
  | [] -> (match ys with
           | [] -> …
           | y::yt -> …)
  | x::xt -> (match ys with
           | [] -> …
           | y::yt -> …)

Alternatively, it's often nicer to match on the pair of inputs; it depends how coupled the two inputs are.

let rec mux xs ys =
  match xs, ys with
  | [], [] -> …
  | [], y::yt -> …
  | x::xt, [] -> …
  | x::xt, y::yt -> …

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM