简体   繁体   中英

Haskell Data Structure

I am trying to build a data-structure in Haskell which functions can use to avoid re-computing values. For example, say I had the function:

f :: Int -> Int -> Int
f 1 1 == 1
f m n
    | abs m > n = 0
    | OTHERWISE if value of f m n has already been computed by another recursive branch, return that value and add it to the "database"
    | OTHERWISE return f (m-1) (n-1) + f (m - 1) n

I have already looked at memoization, but haven't been able to implement a solution :\\

Suggestions? :)

A great explanation is here .

I love memoize package :)

Example (solving the "A frog is jumping up the staircase..." problem):

import Data.Function.Memoize 

ladder :: Integer -> Integer -> Integer 
ladder n k = g n 
  where g = memoize f 
        f 0 = 1 
        f x = sum [g (x - y) | y <- [1..if x < k then x else k]] 

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