[Haskell] Newbie: fix

David House dmhouse at gmail.com
Wed May 2 12:55:50 EDT 2007


On 02/05/07, phiroc at free.fr <phiroc at free.fr> wrote:
> Hello,
>
> could someone please explain why "fix" is necessary here:
>
> fix (\f l -> if null l then [] else let (s,e) = break (==' ') l in s:f (drop 1
> e))
>
> Source: http://www.haskell.org/haskellwiki/Blow_your_mind

Because you're writing a recursive function. If you just had:

if null l then [] else let (s,e) = break (==' ') l in s:XXX (drop 1 e)

Then what goes in place of 'XXX'? There's no name for this particular
bit of code, so you can't call it. Using fix allows you to attach a
name to an arbitrary expression so that you can call it recursively.
The following would work exactly the same:

words :: String -> [String]
words l = if null l then [] else let (s,e) = break (==' ') l in
s:words (drop 1 e)

-- 
-David House, dmhouse at gmail.com


More information about the Haskell mailing list