# [Haskell-beginners] self recursive lambda

sarfraz dragoon.empire at yahoo.fr
Mon Apr 9 20:13:48 CEST 2012

```Ok thanks, got it working:

import System.IO
import Control.Monad.Fix

nHead :: Int -> String -> String
nHead n str = let rec = \x n str -> if n == 0 then str else x (n - 1) (tail str)
in if (length str) < n then str else fix rec n str

main = interact (nHead 5)

In the end I will be using:

import System.IO

nHead :: Int -> String -> String
nHead n str = let rec n str = if n == 0 then str else x (n - 1) (tail str)
in if (length str) < n then str else rec n str

main = interact (nHead 5)

But it's good to know that it was possible.

On Mon, Apr 09, 2012 at 12:28:42PM -0500, Antoine Latter wrote:
> 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
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners

--
Sarfraz K.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 490 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120409/cce5c9c6/attachment.pgp>
```

More information about the Beginners mailing list