[Haskell-beginners] self recursive lambda
Antoine Latter
aslatter at gmail.com
Mon Apr 9 19:28:42 CEST 2012
On Mon, Apr 9, 2012 at 10:57 AM, sarfraz <dragoon.empire at yahoo.fr> wrote:
> Hi,
>
> Can't seem to be able to debug the following:
>
> import System.IO
>
> nHead :: Int -> String -> String
> nHead n str = if (length str) < n
> then str
> else if n ==0
> then str
> else (\x n str -> if n == 0
> -- this lambda does not work
> then str
> else x (n - 1) (tail str))
>
> main = interact (nHead 5)
>
> I see where the problem is. But surely it is possible to make a
> recursive lambda. (I want to use a lambda, i know how to do otherwise)
You can't make a recursive lambda directly - you need a helper function:
http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Function.html#v:fix
Example usage:
> let factNonResursive = \fact n -> if n < 2 then 1 else n * fact (n - 1)
> fix factNonRecursive 5
Antoine
More information about the Beginners
mailing list