Home > front end >  haskell Learn you a haskell chapter 4 example confusing
haskell Learn you a haskell chapter 4 example confusing

Time:11-20

So I started with Learn you a haskell and on chap 4 found and example which did not understand The author writes a function to extract initials from first name and last name

initials :: String -> String -> String  
initials firstname lastname = [f]    ". "    [l]    "."  
    where (f:_) = firstname  
          (l:_) = lastname  


whats the meaning here.. she is combining a list of f with period and list of l and period.. how is she using the helper function? Has she taken (f:_) = firstname because f is the first letter of firstname? Isnt using the head function on both words simpler?

CodePudding user response:

A more understandable way of writing the same thing is

initials firstname lastname = case (firstname, lastname) of
    (f:_, l:_) -> [f]    ". "    [l]    "."  

There's no helper function in the original code, only helper variables f, l :: Char.

Actually the preferred way of writing this is to not even introduce firstname and lastname, but simply pattern-match on them right there:

initials (f:_) (l:_) = [f]    ". "    [l]    "."  

Note also that we still need to handle the case of either list being empty.

initials fn [] = ...?
initials [] ln = ...?

CodePudding user response:

Yes, using the head function is simpler:

initials :: String -> String -> String  
initials firstname lastname = [head firstname]    ". "    [head lastname]    "."  

But [head x] == take 1 x when it works, while head errors for empty inputs and take 1 doesn't, just returning an empty list in such case. So it's preferable to use take 1 here:

initials :: String -> String -> String  
initials firstname lastname = take 1 firstname    ". "    take 1 lastname    "."  
  • Related