Wednesday 15 June 2011

F# Pattern matching and functions -



F# Pattern matching and functions -

i tried implement fibonacci sequence in f# using pattern matching this:

let fibonacci m= allow rec fib = function | (0, _, z) -> z | (n, y, z) -> fib (n-1) z (y+z) fib m 0 1

here expect first argument fib maintain track of how far along in sequence are, , next 2 arguments successive terms in sequence.

however, i'm getting compile-time error on fib (n-1) z (y+z):

type mismatch. expecting 'a -> 'b -> 'c given 'c resulting type infinite when unifying ''a' , ''b -> 'c -> 'a'

i tried specifying types so:

let fibonacci m= allow rec fib = function | (0, _, z:int) -> z | (n:int, y:int, z:int) -> fib (n-1) z (y+z) fib m 0 1

and different compile error on fib (n-1):

this value not function , cannot applied

i'm still trying head around functional programming. think problem might lack of understanding in first pattern means. want mean when position argument zero, returns sec argument term.

could help me problem due basic misunderstanding on part

the problem you're calling function curried arguments when in fact defined expecting tupled arguments:

let fibonacci m = allow rec fib = function | (0, _, z) -> z | (n, y, z) -> fib (n-1, z, y+z) fib (m, 0, 1)

this because using function pattern match single argument, in case against tuple. alternative utilize match

let fibonacci m = allow rec fib b c = match (a, b, c) | (0, _, z) -> z | (n, y, z) -> fib (n-1) z (y+z) fib m 0 1

you can think of function shorthand single argument function followed match on argument.

f# pattern-matching

No comments:

Post a Comment