haskell - flip fix / fix

后端 未结 2 860
春和景丽
春和景丽 2021-02-14 11:10
>>>flip fix (0 :: Int) (\\a b -> putStrLn \"abc\")
Output: \"abc\"

This is a simplified version of using flip fix.
I saw t

2条回答
  •  耶瑟儿~
    2021-02-14 11:33

    This is just a funny way to write a recursive lambda, I can think of two possibilities why this is done:

    • The programmer wanted to confuse newbies.
    • He comes from a language that is more restrictive with recursion (like some LISP, or ML maybe?)

    You could rewrite the code much clearer like:

        loop secret 0
    where
        loop secret numGuesses = do
             putStr "Guess: "
             guess <- getLine
             let
                 score       = calcScore secret guess
                 numGuesses' = numGuesses + 1
             print score
             case scoreRightPos score of
               4 -> putStrLn $ "Well done, you guessed in " ++ show numGuesses'
               _ -> loop secret numGuesses'
    

    The difference being that you must pass the secret manually, which is avoided by the recursive lambda (and this might be another reason to write it with fix)

    For a deeper understanding of fix, goog for "y-combinator"

提交回复
热议问题