lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 09/23/2010 07:36 PM, Patrick Mc(avery wrote:
Hi Scott

Your library looks interesting. I tried to search for more information
about Erlang regular expressions and what they might be best suited for
but I am encountering a rather obvious problem, all the examples are in
Erlang! A language I cannot program in.

Could you tell me a just little bit about Erlang regular expressions and
why someone would want to use them?

Thanks for sharing your code-Patrick


I don't know much about Erlang, but in functional languages, pattern matching doesn't refer to matching text like it does in Lua. Instead, it's matching some value or values against an expression. For example, the Haskell factorial function.

fac :: Int -> Int
fac 1 = 1
fac n = n * fac (n - 1)

When you call "fac 1", it matches the first case ("fac 1") and evaluates it. When you call "fac 2", "fac 3", or something else, it doesn't match "fac 1", so it tries "fac n", which it does match. It binds the given value to n and evaluates the expression. Similarly, with the quicksort:

quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort [x] = [x]
quicksort (x:xs) =
    let smallerSorted = quicksort [a | a <- xs, a <= x]
        biggerSorted = quicksort [a | a <- xs, a > x]
    in  smallerSorted ++ [x] ++ biggerSorted

The expression on the last pattern is a bit confusing, but the patterns basically say:

"For quicksort with an empty list, do this."
"For quicksort with a list of one ordinal x, do this."
"For quicksort with an ordinal x joined to a list of ordinals xs, do this." (: in Haskell joins the object on the left to the list on the right, and ++ is sequence concatenation.)

It makes functional programming a lot more convenient and foolproof.
--
Regards, Matthew "LeafStorm" Frazier
http://leafstorm.us/