• Listen to a special audio message from Bill Roper to the Hive Workshop community (Bill is a former Vice President of Blizzard Entertainment, Producer, Designer, Musician, Voice Actor) 🔗Click here to hear his message!
  • Read Evilhog's interview with Gregory Alper, the original composer of the music for WarCraft: Orcs & Humans 🔗Click here to read the full interview.

[Haskell] Exercises

Status
Not open for further replies.
Well your functions seem correct. However, they are not tail-recursive, you should fix them up to be tail recursive.

Here's my solution but I didn't read the part of text and thought it was all one string xD. Anyways:

Code:
    numberOfPrefix :: String -> [String] -> Int
    numberOfPrefix a b = numPrefixAux a b 0
        where
            numPrefixAux _ [] n = n
            numPrefixAux a (b:bs) n =
                | isPrefix a b = numPrefixAux a bs (n+1)
                | otherwise = numPrefixAux a bs n
    
    numberOfSubstringOcurrence :: String -> String -> Int
    numberOfSubstringOcurrence a b = numSubstringOcurrenceAux a b 0
        where
            numSubstringOcurrenceAux _ [] n = n
            numSubstringOcurrenceAux a b n =
                | isPrefix a b = numSubstringOcurrenceAux a (drop (length a) b) (n+1)
                | otherwise = numSubstringOcurrenceAux a (tail b) n
    
    numberOfPrefixes :: [String] -> [String] -> [(String,Int)]
    numberOfPrefixes l a = numberOfPrefixesAux l a []
        where
            numberOfPrefixesAux [] _ l = l
            numberOfPrefixesAux (h:t) a l = 
                numberOfPrefixesAux t a ((h,(numberOfPrefix h a)):l)
    
    numberOfSubstringOcurrences :: [String] -> String -> [(String,Int)]
    numberOfSubstringOcurrences l a = numSubstringOcurrencesAux l a []
        where
            numSubstringOcurrencesAux [] _ l = l
            numSubstringOcurrencesAux (h:t) a l = 
                numSubstringOcurrencesAux t a ((h,(numberOfPrefix h a)):l)

Now in serious Haskell:
Code:
    isPrefix a b = take (length a) b == a
    numberOfPrefix a b = foldl (\x y -> if isPrefix a y then x + 1 else x) 0 b
    numberOfPrefixes l a = foldl (\x y -> (y,(numberOfPrefix y a)):x) [] l
    numberOfSubstringOcurrence a b = 
        foldl (\x y -> if (isPrefix a y) then x + 1 else x) 0 $ 
            take (length b) $ iterate tail b
    numberOfSubstringOcurrences l a = foldl (\x y -> (y,(numberOfSubstringOcurrence y a)):x) [] l

numberOfPrefix using highorder functions could be better, but I can't think easily on how to do it.

Note: They should be called numberOfOcurrence and numberOfOcurrences, i messed up with what the exercise was asking.

EDIT: ok fixed my stupid mistake.
 
Status
Not open for further replies.
Top