Skip to content

Instantly share code, notes, and snippets.

View wangbj's full-sized avatar

Baojun Wang wangbj

View GitHub Profile
revdigits x = go x 0
where go k r
| k == 0 = r
| otherwise = go d (10*r+m)
where (d, m) = k `quotRem` 10
isPalin x = id x == revdigits x
@wangbj
wangbj / reverseList.c
Created July 9, 2015 01:24
After learnt some haskell..
struct ListNode* uncons (struct ListNode* xxs, struct ListNode** xs)
{
struct ListNode* x = xxs;
if (xxs) {
*xs = xxs -> next;
x -> next = NULL;
}
return x;
g = foldr (.) id chain
where chain = replicate 1000000 succ
@wangbj
wangbj / lp.cc
Created December 15, 2015 22:06
static bool cache[1024][1024];
class Solution {
public:
std::string longestPalindrome(std::string s) {
int sz = (int)s.size();
if (sz == 0) return s;
int start = 0, len = 1;
memset(cache, 0, sizeof(cache));
@wangbj
wangbj / kinds1.hs
Created December 29, 2015 01:10
Play with Haskell Kinds.
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
data Nat = Z | Succ Nat
deriving Show
data Vec :: (* -> Nat -> *) where
Nil :: Vec a Z
import qualified Data.ByteString.Char8 as C
import Data.Maybe
import Text.Printf
readPrice = fromJust . readPrice_
where readPrice_ s = C.readInt s >>= \(x, s1) ->
C.uncons s1 >>= \(c, s2) ->
case c of
'.' -> C.readInt s2 >>= \(y, s3) -> return (x*100+y)
_ -> Nothing
@wangbj
wangbj / viewPatterns1.hs
Created January 14, 2016 19:07
GHC ViewPatterns.
{-# LANGUAGE ViewPatterns #-}
import qualified Data.Sequence as Seq
import Data.Sequence(Seq)
lastr :: Seq a -> Maybe a
lastr (Seq.viewr -> Seq.EmptyR) = Nothing
lastr (Seq.viewr -> s Seq.:> x) = Just x
{-# LANGUAGE PatternSynonyms #-}
import Foreign.C
newtype Mode = MkMode {unMode :: CInt }
pattern Mode0 = MkMode 0
pattern Mode1 = MkMode 1
showIntBase2 = reverse . concatMap show . un
where un = unfoldr go
go = uncurry (*>) . (&&&) (guard . (>0)) (Just . swap . (`quotRem` 2))
-- > showIntBase2 12
-- "1100"
@wangbj
wangbj / foldMap.hs
Created January 22, 2016 08:28
foldMap, fold to monoid
data Tree a = Leaf | Branch a !(Tree a) !(Tree a)
inOrder g Leaf = mempty
inOrder g (Branch a l r) = g a <> inOrder g l <> inOrder g r
instance Foldable Tree where
foldMap g = inOrder g
treeSum :: Tree Integer -> Integer
treeSum = getSum . foldMap Sum