Last active
December 15, 2017 12:25
-
-
Save namratachaudhary/3f9c480b418bc16554ae6669b260181f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data List a = Nothing | Cons a (List a) | |
mylist = (Cons 1 (Cons 2 (Cons 3 Nothing))) | |
print mylist | |
-- This will show errors | |
-- You cannot run a `show` on your mylist | |
-- because you are not deriving them while defining your list in line 1 | |
-- So your new definition becomes | |
data List a = Nothing | Cons a (List a) deriving (Show) | |
mylist = (Cons 1 (Cons 2 (Cons 3 Nothing))) | |
print mylist | |
-- Cons 1 (Cons 2 (Cons 3 Nothing)) | |
-- Maybe read the arrows tutorial> https://wiki.haskell.org/Arrow_tutorial | |
showHead :: List a -> a | |
showHead l = case l of Cons a _ -> a | |
-- showHead mylist => 10 (Not Cons 10) | |
showTail :: List a -> List a | |
showTail Nothing = Nothing | |
showTail l = case l of Cons _ a -> a | |
-- showTail mylist => Cons 99 (Cons 11 Nothing) | |
showLength :: List a -> Int | |
showLength Nothing = 0 | |
showLength xs = 1 + (showLength (showTail xs)) -- I hope this is right :/ | |
-- showLength mylist => 3 | |
-- The evaluations are lazy. If you define the list of infinite length, it will give you head, tail. | |
-- But if you compute length, it will go into stackoverflow. This is concept called - Holding on to the head. | |
-- The program is holding on to the first value and mutating it - infinitely. | |
-- One way to handle it to make your evaluations strict instead of lazy. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment