Created
December 21, 2011 19:08
-
-
Save missingfaktor/1507246 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
! A simple program that generates Excel spreadsheet column id corresponding to given column number. | |
! For example: | |
! 14 - N | |
! 26 - Z | |
! 27 - AA | |
! 29 - AC | |
USING: kernel math math.ranges sequences strings ; | |
IN: excel-columns | |
! Use the following after 'alphabet' definition to make it a compile time constant. | |
! << \ alphabet alphabet define-constant >> | |
: alphabet ( -- seq ) CHAR: A CHAR: Z [a,b] ; | |
: nth-char ( n -- char ) 25 + 26 mod alphabet nth 1string ; | |
: break-26 ( m -- n o ) 26 /mod ; | |
: column-id ( i -- str ) dup 26 <= [ nth-char ] [ break-26 [ column-id ] bi@ append ] if ; | |
: test-run ( -- ) 1000 [1,b] [ dup column-id 2array . ] each ; | |
MAIN: test-run |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Applicative | |
import Control.Arrow | |
import Control.Monad | |
import Control.Monad.Instances | |
import qualified Data.Vector as V | |
-- Y U NO IN STANDARD LIBRARY????!!!! | |
if' :: Bool -> a -> a -> a | |
if' cond x y = if cond then x else y | |
alphabet :: Vector Char | |
alphabet = V.enumFromTo 'A' 'Z' | |
nthChar :: Int -> String | |
nthChar = (:[]) . (alphabet V.!) . (`mod` 26) . (+ 25) | |
break26 :: Int -> (Int, Int) | |
break26 = (`divMod` 26) | |
columnId :: Int -> String | |
columnId = if' <$> (<= 26) <*> nthChar <*> uncurry (++) . join (***) columnId . break26 | |
main :: IO () | |
main = forM_ [1..100] (print . (id &&& columnId)) |
@chris-taylor: Thanks. I wasn't aware of that function. Turns out Factor has /mod
as well. Will update the snippets accordingly.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To write break26 while only using 26 once, why not write