How does the Haskell rec keyword work?

后端 未结 2 1907
终归单人心
终归单人心 2020-12-24 07:42

In arrow do notation, you can use the rec keyword to write recursive definitions. So for example:

rec
    name <- function -< input
    input <- oth         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 08:04

    Here is a real-ish example:

    loop f b = let (c,d) = f (b,d) in c
    
    f (b,d) = (drop (d-2) b, length b)
    
    main = print (loop f "Hello World")
    

    This program outputs "ld". The function 'loop f' takes one input 'b' and creates one output 'c'. What 'f' is doing is studying 'b' to produce 'length b' which is getting returned to loop and bound to 'd'.

    In 'loop' this 'd=length b' is fed into the 'f' where it is used in the calculation in drop.

    This is useful for tricks like building an immutable doubly linked list (which may also be circular). It is also useful for traversing 'b' once to both produce some analytic 'd' (such as length or biggest element) and to build a new structure 'c' that depends on 'd'. The laziness avoids having to traverse 'b' twice.

提交回复
热议问题