[Haskell-beginners] Data type

Alex Hammel ahammel87 at gmail.com
Tue May 5 16:11:00 UTC 2015


Sticking with the Person example, we might want to use a dynamically-bound
function to specify a different greeting message for different values of
Person:

data Person = Person { name :: String , greet :: Person -> String }

anne = Person "Anne" (\p -> "Howdy, " ++ name p ++ ".")
bob = Person "Bob" (\p -> "Hi, " ++ name p ++ "! I'm Bob")
carol = Person "Carol" (\_ -> "'Sup?")

main = do
    putStrLn $ anne `greet` bob
    putStrLn $ bob `greet` carol
    putStrLn $ carol `greet` anne

You could even get really crazy and construct the greeting function at
runtime:

main = do
    putStr "Enter a name: "
    n <- getLine
    putStrL"Enter a greeting: "
    greeting <- getLine

    let user = Person n (\p -> concat [greeting, ", ", name p, "!"])
        bob = Person "Bob" (\p -> concat ["Hello, ", name p, "!"])

    putStrLn $ bob `greet` user
    putStrLn $ user `greet` bob

$ runhaskell test.hs
Enter a name: Morbo
Enter a greeting: I WILL DESTROY YOU
Hello, Morbo!
I WILL DESTROY YOU, Bob!

On Tue, 5 May 2015 at 08:38 Shishir Srivastava <shishir.srivastava at gmail.com>
wrote:

> Hi Brandon,
>
> Thanks for your response. My example was just a bad turnout which I
> conjured up using tutorials and playing with it.
>
> I was going to follow up my question with the possible practical use of
> why and where someone would use such a construct to wrap a function inside
> a new data-type.
>
> For all that matters I could have used 'length' function directly to get
> the same output.
>
> I appreciate that you already have given the practical example but
> anything more basic for beginners to highlight the usage would be helpful.
>
> Thanks,
> Shishir
>
>
> On Tue, May 5, 2015 at 4:28 PM, Shishir Srivastava <
> shishir.srivastava at gmail.com> wrote:
>
>> Thanks Matthew - that was crisp !
>>
>> Cheers,
>> Shishir
>>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150505/17e1069d/attachment.html>


More information about the Beginners mailing list