2025-10-20 Daily Worksheet

Assorted practice, including let, Maybe, higher order functions.

Review

  1. Inside a function f x, use let to create variables x2 holding x squared, and x3 holding x cubed. Then create the function below.

    $$ f(x) = x^3 (x^2-1) $$

Semi-New

An official data type is Maybe a. The data definition is:

    data Maybe a = Nothing | Just a
        deriving (Show, Eq, ...)

Do not recopy that code; it is built into the Haskell interpreter that we use.

  1. Write a function g2 that takes in a Maybe Int and returns 0 if it is given Nothing and otherwise 10 more than the absolute value of the int.

      checks_2 = [   0 == g2 Nothing
                  , 12 == g2 (Just 2)
                  , 25 == g2 (Just 15) ]
    
  2. Write a function h2 that takes in a Maybe String and puts out a Maybe String, doubling the string if it exists.

      check_h2 = [ Just "mommom" == h2 (Just "mom")
                  , Nothing == h2 Nothing ]
    

Higher Order Functions

  1. (myor) The or function returns True when any item in a list is True; otherwise it returns False. Use foldl to create your own version of this function.

     myor :: [Bool] -> Bool
    
  2. Use recursion to write a function myall that applies a function to every item in a list, and returns True if every function application returns True.

     myall :: (a -> Bool) -> [a] -> Bool
     check_myall = [ myall even [2,4,10,20] == True
                    ,myall (<5) [1,3,6,2,4] == False
                    ]
    
Last modified October 31, 2025: Haskell quizzes including CodeWorld. (c5c8b02)