Skip to content

Instantly share code, notes, and snippets.

@zxexz
Created October 28, 2017 04:28
Show Gist options
  • Save zxexz/af787fe8e5b122fca20f4486349d8258 to your computer and use it in GitHub Desktop.
Save zxexz/af787fe8e5b122fca20f4486349d8258 to your computer and use it in GitHub Desktop.
import Data.List (group, sort)
import Control.Arrow ((&&&))
nGrams :: Int -> [a] -> [[a]]
nGrams x xs
| null xs = [[]]
| x <= 0 = [[]]
| x == 1 = [[y] | y <- xs]
| x == 2 = map (\ (x, y) -> [x, y]) $ zip xs $ tail xs
| otherwise = zipWith (:) xs (nGrams (x - 1) $ tail xs)
bigrams :: [a] -> [[a]]
bigrams = nGrams 2
countNGrams :: (Ord a) => Int -> [[a]] -> [([a], Int)]
countNGrams x xss = map (head &&& length) . group $ sort [xs | xs <- xss, length xs == x || x < 0 ]
countBigrams' :: (Ord a) => [a] -> [([a], Int)]
countBigrams' = countNGrams 2 . nGrams 2
-- -for E58 assignment
countBigrams :: String -> [(String, Int)]
countBigrams xs = map (fst &&& (\ (_, y) -> y - 1)) $ countNGrams 2 $ [ [x, y] | x <- "ATCG", y <- "ATCG" ] ++ nGrams 2 "ATCG"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment