Skip to content

Instantly share code, notes, and snippets.

@namratachaudhary
Last active December 15, 2017 12:25
Show Gist options
  • Save namratachaudhary/3f9c480b418bc16554ae6669b260181f to your computer and use it in GitHub Desktop.
Save namratachaudhary/3f9c480b418bc16554ae6669b260181f to your computer and use it in GitHub Desktop.

Revisions

  1. namratachaudhary revised this gist Dec 15, 2017. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions LinkedList.hs
    Original file line number Diff line number Diff line change
    @@ -3,11 +3,11 @@ mylist = (Cons 1 (Cons 2 (Cons 3 Nothing)))
    print mylist
    -- This will show errors

    -- You cannot run a `show` or `eq` on your mylist
    -- 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, Eq)
    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))
  2. namratachaudhary created this gist Dec 15, 2017.
    37 changes: 37 additions & 0 deletions LinkedList.hs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    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` or `eq` 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, Eq)
    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.