-1

I am trying to achieve the following (defined in Javascript) in Haskell: JS:

const fold = (c, h) => {
  const f = (n) => {
    return n === 0 ? c : h (f(n-1))
  }
  return f
}

fold(1, (x)=>x*10)(3)

Repl Link: https://repl.it/repls/ExperiencedTeemingLorikeet

I tried something along these lines (but does not work):

foldn c h =
 f  = f' n
      where f' 0 = c
            f' n =  h(f'(n-1))
 f

Essentially I am trying to create a named curried function "f" that can be returned. Also note that the definition of "f" is recursive How can I do this in Haskell?

coder_bro
  • 10,503
  • 13
  • 56
  • 88

2 Answers2

1

Actually, all functions in Haskell are curried by default, so you can just do

fold c h n = if n == 0 then c else h (fold c h (n-1))

If you still prefer to have an f inside, then

fold c h = f
    where
        f 0 = c
        f n = h (f (n-1))

These versions are equivalent, and can be called like

fold 1 (*10) 3
lisyarus
  • 15,025
  • 3
  • 43
  • 68
1

You're close. Just declare a function that closes over c and h.

foldn c h = f where
  f 0 = c
  f n =  h . f $ n-1
pat
  • 12,587
  • 1
  • 23
  • 52