Day 4: Haskell

TLDR : Failing Spectacularly

CaptainLazarus
2 min readDec 27, 2021

Following this video. Will probably go on hackerrank and codechef later and solve a few questions there too.

One more thing. Just like python, Haskell will throw a hissy fit if indentation isn’t right, so careful with that.

  1. Create a function elem that returns True if an element is in a list and False if it isn’t.

My solution

el xs a
| xs == [] = False
| otherwise = if (head xs) == a then True else el (tail xs) a

The solution given

elem _ [] = False
elem e (x:xs) = (e == x) || (elem e xs)

Comments : I’m writing it like I’m writing a function in python, base case and other recursive. Forgot completely about pattern matching. Probably have to get used to it.

2. Create a function that removes duplicates from a list.

My solution

-- Problem 2
nub1 xs
| xs == [] = []
| otherwise = if elem (head xs) (tail xs) then nub1 tail xs else ......
Tried something like this too
nub1 xs = [head xs | x <- xs , el1 (head xs) (tail xs)]

If you’re wondering what the “….” means, it means that I looked at the solution because I had no idea what to do. I knew I had to recursively look at the list, I just didn’t know how to proceed to do it. Giving the solution below.

nub2 [] = []nub2 (x:xs)
| elem x xs = nub2 xs
| otherwise = x:(nub2 xs)

I forgot the frustrations of learning the small stuff. I also assumed that (x:xs) wasn’t a list (the function definitions were given beforehand, and I assumed it was 2 lists), so I tried to avoid it. Turns out it is. That too is something to keep in mind.

3. Create a function isAsc if the function given to it is in ascending order.

My Solution (didn’t work)

-- Problem 3isAsc [] = True
isAsc (x:xs)
| x >= (head xs) = isAsc xs
| x < (head xs) = False

The actual solution

isAsc [] = True
isAsc [x] = True
isAsc (x:y:xs) = (x <= y) && isAsc (y:xs)

I’m starting to like these solutions, if only because of how intuitive they are. Sadly, I need to practice this stuff.

--

--

CaptainLazarus

I do stuff. Like stuff about code. And book stuff. And gaming stuff. And stuff about life. And stuff about stuff.