반응형
목록과 구분자를 연결하는 haskell 기능이 있나요?
리스트의 요소를 구분자로 연결하는 기능이 있습니까?예를 들어 다음과 같습니다.
> foobar " " ["is","there","such","a","function","?"]
["is there such a function ?"]
답장 감사합니다!
Prelude> import Data.List
Prelude Data.List> intercalate " " ["is","there","such","a","function","?"]
"is there such a function ?"
intersperse
조금 더 일반적입니다.
Prelude> import Data.List
Prelude Data.List> concat (intersperse " " ["is","there","such","a","function","?"])
"is there such a function ?"
또, 스페이스 문자를 사용해 결합하는 경우는, 다음과 같습니다.
Prelude> unwords ["is","there","such","a","function","?"]
"is there such a function ?"
unlines
마찬가지로 동작하는 것은 문자열이 newline 문자를 사용하여 삽입되고 newline 문자가 끝에 추가되는 경우뿐입니다(이를 통해 POSIX 표준 말미에 후행의 newline이 있는 텍스트파일 시리얼화에 도움이 됩니다).
폴더를 사용하여 원라이너를 쓰는 것은 어렵지 않습니다.
join sep xs = foldr (\a b-> a ++ if b=="" then b else sep ++ b) "" xs
join " " ["is","there","such","a","function","?"]
관심이 있는 경우, 인터스페스 및 인터컬레이트 구현에 대한 몇 가지 다른 아이디어:
myIntersperse :: a -> [a] -> [a]
myIntersperse _ [] = []
myIntersperse e xs = init $ xs >>= (:[e])
myIntercalate :: [a] -> [[a]] -> [a]
myIntercalate e xs = concat $ myIntersperse e xs
xs >>= f
와 동등하다concat (map f xs)
.
joinBy sep cont = drop (length sep) $ concat $ map (\w -> sep ++ w) cont
자신의 버전을 쓰고 싶다면intercalate
그리고.intersperse
:
intercalate :: [a] -> [[a]] -> [a]
intercalate s [] = []
intercalate s [x] = x
intercalate s (x:xs) = x ++ s ++ (intercalate s xs)
intersperse :: a -> [a] -> [a]
intersperse s [] = []
intersperse s [x] = [x]
intersperse s (x:xs) = x : s : (intersperse s xs)
언급URL : https://stackoverflow.com/questions/9220986/is-there-any-haskell-function-to-concatenate-list-with-separator
반응형
'programing' 카테고리의 다른 글
간단한 HTML 쓰는 법Drop Down List For()? (0) | 2023.04.22 |
---|---|
파일 또는 어셈블리 'Newtonsoft'를 로드할 수 없습니다.Json, 버전=4.5.0.0, Culture=중립, PublicKey토큰=30ad4fe6b2a6aed' (0) | 2023.04.22 |
어떻게 하면 더블을 가장 가까운 인터로 빠르게 반올림 할 수 있을까요? (0) | 2023.04.22 |
Swift로 입력된 어레이를 확장하려면 어떻게 해야 합니까? (0) | 2023.04.22 |
shell 명령어를 명령어 출력의 각 행에 적용하려면 어떻게 해야 합니까? (0) | 2023.04.22 |