1
-- | Days of week.
data Day = Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday deriving (Eq, Show)

-- | Returns the next weekday (excluding weekend, namely Saturday and Sunday).
nextWeekday :: Day -> Day
nextWeekday day = 
  if x == Sunday
    then let x = Monday
  if x == Monday 
    then let x = Tuesday
  if x == Tuesday
    then let x = Wednesday
  if x == Wednesday
    then let x = Thursday
  if x == Thursday
    then let x = Friday
  if x == Friday
    then let x = Saturday
  else
    then let x = Sunday

This my code right now... What's wrong with this code...? How can I auto-indent the Haskell code?

proceeder
  • 25
  • 4
  • relevant: https://stackoverflow.com/questions/20294273/less-redundant-way-to-make-instances-of-a-circular-enum-typeclass – rajashekar Oct 02 '21 at 13:54
  • what's wrong with your code is that `let` is not `set`. Haskell's variables can't be changed. see https://stackoverflow.com/questions/11922134/how-to-increment-a-variable-in-functional-programming. – Will Ness Oct 02 '21 at 15:12

1 Answers1

2

An if … then … else … in Haskell always has an else clause, since you write an expression and for the two possible outcomes of the condition, it should return a value.

Furthermore you use if x == Monday, but x is not an input parameter. You also use let x = Monday, but then you need to use an in clause. While let x = Monday in x is valid, we can simply use Monday instead of working with a helper variable x. You thus can implement this as:

nextWeekday :: Day -> Day
nextWeekday day = 
  if day == Sunday
    then Monday
  else if day == Monday 
    then Tuesday
  else if day == Tuesday
    then Wednesday
  else if day == Wednesday
    then Thursday
  else if day == Thursday
    then Friday
  else if day == Friday
    then Saturday
  else Sunday

Often it is however better to work with pattern matching than branching, so we can implement this as:

nextWeekDay :: Day -> Day
nextWeekDay Sunday = Monday
nextWeekDay Monday = Tuesday
nextWeekDay Tuesday = Wednesday
nextWeekDay Wednesday = Thursday
nextWeekDay Thursday = Friday
nextWeekDay Friday = Saturday
nextWeekDay Saturday = Sunday
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 1
    Even easier would be to derive `Enum` for the `Day` datatype and use `succ`, although you'd have to write a small custom function to modify it to "wrap around" from Saturday to Sunday. – Robin Zigmond Oct 02 '21 at 13:47
  • 2
    @RobinZigmond: yes, I considered to mention this in the answer, but I guess the exercise right now the OP is trying to complete focusses more on the syntax than on the `Enum` typeclass. – Willem Van Onsem Oct 02 '21 at 14:02