Jump to content

Could somebody help me with understanding this basic Haskell code? Thanks!

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
AlexY

AlexY

    Newbie

  • Members
  • Pip
  • 2 posts
The question is:
1. (a) The function ord :: Char -> Int converts a character to its corresponding
ASCII code. For example,
ord ’A’ = 65 ord ’B’ = 66 ... ord ’Z’ = 90
ord ’a’ = 97 ord ’b’ = 98 ... ord ’z’ = 122
Using ord, write a function f :: Char -> Int that converts a letter, lower case
or upper case, to its ordinal position in the alphabet. For example,
f ’A’ = 0 f ’B’ = 1 ... f ’Z’ = 25
f ’a’ = 0 f ’b’ = 1 ... f ’z’ = 25
For any character that is not a letter, f should return an error.

The solution is below and I stop understanding it right after ''a' <= x && x <= 'z' =' on the first line. Could somebody please walk me through exactly what is happening here? Thank you in advance.
-- 1a.

f :: Char -> Int
f x | 'a' <= x && x <= 'z' = ord x - ord 'a'
| 'A' <= x && x <= 'Z' = ord x - ord 'A'

x1a = f 'A' == 0 && f 'B' == 1 && f 'Z' == 25 &&
f 'a' == 0 && f 'b' == 1 && f 'z' == 25

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
What it's doing is looking at two cases.
Case 1: x between 'a' and 'z', returns ord x - ord 'a'
Case 2: x between 'A' and 'Z', returns ord x - ord 'A'
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
AlexY

AlexY

    Newbie

  • Members
  • Pip
  • 2 posts
Thank you. I understand it now :) I was just a little confused. Thanks for the help. One last question

c :: [Int] -> [Int] -> [Int]
c xs ys | length xs == length ys = [ x-y | (x,y) <- zip xs ys ]

I understand that C takes two lists of xs and ys and then there is a guard(?) after which it makes sure that the length of the two lists are equal. Then it becomes a list comprehension?
I am getting a little confused with the syntax, because I thought that length xs == length ys would be the condition or 'check' to makes sure that the two lists of equal, that it should go inside the square brackets. So something like this: (additionally why is x not drawn from xs and y not drawn from ys?)
c xs ys = [ x-y | x<-xs, y<-ys, length xs == length ys]

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
The best thing you can do is compare your two results on sample data. In general, zip pairs the elements of xs and ys in order, whereas grabbing the individual elements will generate all possible pairings.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog