Haskell The Craft Of Functional Programming Solutions
Introduction
Haskell is a programming language that has been gaining popularity in recent years. It is a functional programming language that is known for its elegant syntax and strong type system. The language is named after the logician Haskell Curry and is based on the lambda calculus. Haskell has been around for over 30 years and has evolved into a mature language with a strong community. In this article, we will explore some of the solutions to common programming problems in Haskell.
Problem: FizzBuzz
FizzBuzz is a classic programming problem that involves printing the numbers from 1 to 100. However, for multiples of three, you should print "Fizz" instead of the number and for multiples of five, you should print "Buzz". For numbers that are multiples of both three and five, you should print "FizzBuzz".
In Haskell, we can solve this problem using pattern matching and guards. Pattern matching allows us to match specific values and guards allow us to add conditions to the match. Here's the solution:
fizzBuzz :: Int -> StringfizzBuzz n| n `mod` 15 == 0 = "FizzBuzz"| n `mod` 3 == 0 = "Fizz"| n `mod` 5 == 0 = "Buzz"| otherwise = show nmain = mapM_ (putStrLn . fizzBuzz) [1..100]
Problem: Fibonacci Sequence
The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers. The sequence starts with 0 and 1, and the next number in the sequence is the sum of the previous two numbers.
In Haskell, we can solve this problem using recursion. We define a function that takes an integer n and returns the nth number in the Fibonacci sequence. Here's the solution:
fibonacci :: Int -> Intfibonacci 0 = 0fibonacci 1 = 1fibonacci n = fibonacci (n-1) + fibonacci (n-2)main = print (fibonacci 10)
Problem: Palindrome
A palindrome is a word, phrase, number or other sequence of characters that reads the same forwards and backwards. For example, "racecar" is a palindrome.
In Haskell, we can solve this problem by converting the string to a list of characters and then comparing the first and last characters. We continue doing this until we have compared all the characters. Here's the solution:
isPalindrome :: String -> BoolisPalindrome [] = TrueisPalindrome [x] = TrueisPalindrome (x:xs) = (x == last xs) && (isPalindrome (init xs))main = doputStrLn (show (isPalindrome "racecar"))putStrLn (show (isPalindrome "hello"))
Conclusion
Haskell is a powerful and elegant programming language that is well-suited to solving complex problems. In this article, we explored some of the solutions to common programming problems in Haskell. By using functional programming concepts such as recursion, pattern matching and guards, we were able to write concise and efficient code. If you are interested in learning more about Haskell, there are many resources available online and in print.