开发者

n+k patterns in F#?

I wrote the following in F#:

let fib x = 
  match x with
  | 0 -> 0
  | 1 -> 1
  | n+2 -> fib n + fib (n+1)

Unfortunately, I got a compiler error stating I had used an infix operator in an unexpected place. Other than using the wildcard charac开发者_开发技巧ter, is there a way I can express my intent in F#?


You can get that by definining an active pattern. I'm not exactly sure how n+k patterns work with Haskell (e.g. can they ever fail?), but the following should be a good start:

// Result of matching 'input' against 'add + k'
let (|PlusNum|) add input = 
  input - add

let rec fib = function
  | 0 -> 0 
  | 1 -> 1 
  | PlusNum 2 n -> fib n + fib (n+1)

EDIT: Based on the comment by sepp2k, here is an updated version that fails if "n" would be negative:

// Result of matching 'input' against 'add + k'
let (|PlusNum|_|) add input = 
  if input - add < 0 then None 
  else Some(input - add)


F# doesn't support n+k patterns, but you can rewrite it in terms of just n:

let rec fib x =
    match x with
    | 0 -> 0
    | 1 -> 1
    | n -> fib (n - 2) + fib (n - 1)

Note that recursive functions in F# need the rec keyword, unlike in Haskell.


I would subtract -2 on both sides. And you have to add the rec keyword, because you are declaring a recursive function.

so you get:

let rec fib x =
    match x with
    | 0 -> 0
    | 1 -> 1
    | n -> fib (n - 2) + fib (n - 1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜