开发者

Longest common subsequence (Haskell)

I've been 开发者_开发百科struggling with this for a while. I'm solving the longest common subsequence problem in Haskell as a learning exercise.

I have a function f1 that is passed two Ints i and j, and a function f2. f1 builds a two dimensional list so that the (i,j) location in the list is equal to f2 i j.

Now I'm trying to write a function called lcs that takes two Strings s1 and s2 and finds the longest common subsequence using f1 for memoization.

I'm not exactly sure how to set this up. Any ideas?

Code:

f1 :: Int -> Int -> (Int -> Int -> a) -> [[a]]

f2 :: Int -> Int -> a

lcs:: String -> String -> Int


I assume the Int parameters of f1 are some sort of bounds? Remember that using lists give you the benefit of not needing to specify bounds (because of laziness), but it costs you slow access times.

This function should do what you want f1 to do (memoize a given function):

memo :: (Int -> Int -> a) -> (Int -> Int -> a)
memo f = index where
  index x y = (m !! x) !! y
  m         = [[f x y|y <- [0..]]|x <- [0..]]

-- memoized version of f2
f2' = memo f2
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜